Advanced List Techniques
Functional Programming Approaches
List Comprehensions
## Transform and filter lists efficiently
numbers = [1, 2, 3, 4, 5]
squared_evens = [x**2 for x in numbers if x % 2 == 0]
Advanced Ordering Techniques
import itertools
## Permutations and combinations
items = [1, 2, 3]
permutations = list(itertools.permutations(items))
List Manipulation Methods
Method |
Description |
Example |
map() |
Apply function to all elements |
doubled = list(map(lambda x: x*2, numbers)) |
filter() |
Select elements based on condition |
evens = list(filter(lambda x: x % 2 == 0, numbers)) |
Functional Sorting Techniques
graph TD
A[Advanced Sorting] --> B[Lambda Functions]
A --> C[Functional Methods]
B --> D[Custom Sorting]
C --> E[Transformation]
Custom Sorting with Complex Logic
## Advanced sorting with multiple criteria
data = [
{'name': 'Alice', 'age': 30, 'score': 85},
{'name': 'Bob', 'age': 25, 'score': 90}
]
## Sort by multiple attributes
sorted_data = sorted(
data,
key=lambda x: (-x['score'], x['age']),
reverse=True
)
Memory-Efficient Techniques
Generator Expressions
## Memory-efficient list processing
large_list = range(1000000)
processed = (x**2 for x in large_list if x % 2 == 0)
LabEx recommends using functional methods for complex list manipulations to improve code readability and performance.
Advanced Ordering Strategies
Partial Sorting
import heapq
## Efficiently find top N elements
numbers = [5, 2, 8, 1, 9, 3]
top_three = heapq.nlargest(3, numbers)
Error Handling and Edge Cases
## Safe list processing
def safe_process(items):
try:
return [x for x in items if isinstance(x, (int, float))]
except TypeError:
return []
Technique |
Time Complexity |
Memory Usage |
List Comprehension |
O(n) |
Moderate |
map() |
O(n) |
Low |
filter() |
O(n) |
Low |