Index Manipulation Tricks
Dynamic Index Modification
Inserting Elements at Specific Indexes
## Insert element at specific index
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, 'grape')
print(fruits) ## Output: ['apple', 'grape', 'banana', 'cherry']
Replacing Elements Using Indexes
## Replace element at specific index
numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers) ## Output: [1, 2, 10, 4, 5]
Advanced Index Operations
Index-based Deletion
## Remove element by index
colors = ['red', 'green', 'blue', 'yellow']
del colors[1]
print(colors) ## Output: ['red', 'blue', 'yellow']
Finding Index Positions
## Find index of an element
fruits = ['apple', 'banana', 'cherry', 'banana']
print(fruits.index('banana')) ## Output: 1
print(fruits.index('banana', 2)) ## Output: 3 (search after index 2)
Index Manipulation Strategies
graph TD
A[Index Manipulation] --> B[Insertion]
A --> C[Replacement]
A --> D[Deletion]
A --> E[Searching]
Index Manipulation Techniques
Technique |
Method |
Description |
Insert |
list.insert(index, element) |
Add element at specific position |
Replace |
list[index] = new_value |
Change element at given index |
Delete |
del list[index] |
Remove element at specific index |
Search |
list.index(element) |
Find first occurrence of element |
Complex Index Manipulation
## Swapping elements using indexes
numbers = [1, 2, 3, 4, 5]
numbers[0], numbers[-1] = numbers[-1], numbers[0]
print(numbers) ## Output: [5, 2, 3, 4, 1]
## Conditional index manipulation
data = [10, 20, 30, 40, 50]
data = [x if x > 25 else 0 for x in data]
print(data) ## Output: [0, 0, 30, 40, 50]
Safe Index Handling
def safe_get_index(lst, index, default=None):
try:
return lst[index]
except IndexError:
return default
numbers = [1, 2, 3]
print(safe_get_index(numbers, 5, 'Not Found')) ## Output: Not Found
Key Takeaways
- Python offers multiple ways to manipulate list indexes
- Always handle potential index errors
- Use built-in methods for safe index operations
LabEx recommends practicing these techniques to become proficient in list manipulation.