Efficient Manipulation Methods
Advanced List Manipulation Techniques
Unpacking and Slicing
## Advanced unpacking
nested = [1, [2, 3, 4], 5]
first, [*middle], last = nested
## Powerful slicing techniques
complex_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
reversed_list = complex_list[::-1]
every_second = complex_list[::2]
Functional Manipulation Methods
Map and Filter Functions
## Map function for transformation
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
## Filter function for selection
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
Nested List Operations
import copy
## Deep copy of nested lists
original = [[1, 2], [3, 4]]
deep_copied = copy.deepcopy(original)
## Nested list transformation
transformed = [
[x * 2 for x in sublist]
for sublist in original
]
Method |
Time Complexity |
Memory Usage |
Flexibility |
List Comprehension |
O(n) |
Moderate |
High |
Map/Filter |
O(n) |
Low |
Moderate |
Numpy Operations |
O(n) |
Efficient |
Very High |
Advanced Manipulation Strategies
graph TD
A[List Manipulation] --> B[Transformation]
A --> C[Filtering]
A --> D[Aggregation]
B --> E[Map Function]
C --> F[Filter Function]
D --> G[Reduce Function]
Reducing and Aggregating
from functools import reduce
## Reduce for complex aggregations
nested_list = [[1, 2], [3, 4], [5, 6]]
total_sum = reduce(lambda x, y: x + sum(y), nested_list, 0)
## Advanced aggregation
def complex_aggregation(nested_data):
return [
sum(sublist)
for sublist in nested_data
]
result = complex_aggregation(nested_list)
Memory-Efficient Techniques
## Generator expressions for large datasets
def memory_efficient_processing(large_nested_list):
return (
sum(sublist)
for sublist in large_nested_list
)
## Lazy evaluation
lazy_result = list(memory_efficient_processing([[1,2],[3,4]]))
- Use generator expressions for large datasets
- Prefer list comprehensions over traditional loops
- Utilize functional programming methods
- LabEx recommends profiling your specific use cases
Error Handling in List Manipulation
def safe_nested_manipulation(nested_list):
try:
return [
max(sublist)
for sublist in nested_list
if sublist
]
except (TypeError, ValueError) as e:
print(f"Error in list manipulation: {e}")
return []
Advanced Sorting Techniques
## Complex nested list sorting
complex_list = [[3, 2], [1, 4], [5, 1]]
sorted_list = sorted(complex_list, key=lambda x: sum(x))