List Manipulation Techniques
Basic List Manipulation Methods
Adding Elements
## Append: Add to end of list
fruits = ['apple', 'banana']
fruits.append('cherry')
## Insert: Add at specific position
fruits.insert(1, 'blueberry')
## Extend: Add multiple elements
fruits.extend(['date', 'elderberry'])
Removing Elements
## Remove specific element
fruits.remove('banana')
## Remove by index
deleted_fruit = fruits.pop(2)
## Clear entire list
fruits.clear()
Sorting Lists
## Ascending sort
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort() ## In-place sorting
## Descending sort
numbers.sort(reverse=True)
## Sorted function (returns new list)
sorted_numbers = sorted(numbers)
List Comprehensions
## Create list of squares
squares = [x**2 for x in range(1, 6)]
## Filtering list
even_numbers = [x for x in range(10) if x % 2 == 0]
Advanced Manipulation Techniques
Mapping and Filtering
## Map function
def double(x):
return x * 2
numbers = [1, 2, 3, 4, 5]
doubled = list(map(double, numbers))
## Filter function
def is_even(x):
return x % 2 == 0
even_nums = list(filter(is_even, numbers))
List Operations
Operation |
Method |
Description |
Reverse |
reverse() |
Reverse list in-place |
Count |
count() |
Count occurrences |
Index |
index() |
Find element position |
Copying Lists
## Shallow copy
original = [1, 2, 3]
shallow_copy = original.copy()
## Deep copy
import copy
deep_copy = copy.deepcopy(original)
List Slicing Techniques
numbers = [0, 1, 2, 3, 4, 5]
## Basic slicing
subset = numbers[2:4] ## [2, 3]
## Step slicing
every_second = numbers[::2] ## [0, 2, 4]
## Reverse list
reversed_list = numbers[::-1] ## [5, 4, 3, 2, 1, 0]
List Manipulation Flow
graph TD
A[List Manipulation] --> B[Adding Elements]
A --> C[Removing Elements]
A --> D[Sorting]
A --> E[Filtering]
A --> F[Transforming]
Nested List Manipulation
## Flattening nested list
nested = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested for item in sublist]
- Use list comprehensions for efficiency
- Avoid repeated list modifications
- Choose appropriate methods for large lists
By mastering these techniques in LabEx Python environments, you'll become proficient in list manipulation and data processing.