List Manipulation Techniques
Mapping Elements
## Transform list elements using map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
Filtering Lists
## Filter list elements conditionally
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
List Concatenation and Multiplication
## Combining lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2 ## [1, 2, 3, 4, 5, 6]
## Repeating lists
repeated = list1 * 3 ## [1, 2, 3, 1, 2, 3, 1, 2, 3]
Advanced Unpacking Techniques
## Unpacking lists
first, *rest = [1, 2, 3, 4, 5]
## first = 1, rest = [2, 3, 4, 5]
List Manipulation Strategies
Technique |
Method |
Example |
Flattening |
List Comprehension |
flat = [x for sublist in nested for x in sublist] |
Removing Duplicates |
Set Conversion |
unique = list(set(original_list)) |
Sorting |
Custom Key |
sorted(list, key=lambda x: x[1]) |
Nested List Operations
flowchart TD
A[Nested List] --> B[Flatten]
B --> C[Transform]
C --> D[Filter]
## Complex nested list manipulation
nested = [[1, 2], [3, 4], [5, 6]]
flattened = [num for sublist in nested for num in sublist]
Efficient List Copying
## Shallow copy
original = [1, 2, 3]
shallow_copy = original.copy()
## Deep copy
import copy
deep_copy = copy.deepcopy(original)
List Rotation and Shifting
def rotate_list(lst, k):
k = k % len(lst)
return lst[-k:] + lst[:-k]
numbers = [1, 2, 3, 4, 5]
rotated = rotate_list(numbers, 2) ## [4, 5, 1, 2, 3]
LabEx Insight
Mastering list manipulation techniques is crucial for efficient Python programming. LabEx recommends practicing these methods to improve your coding skills.