Advanced List Generation
Sophisticated List Generation Techniques
1. Nested List Comprehensions
## Creating a matrix
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
## Result: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
## Flattening nested lists
flattened = [num for sublist in matrix for num in sublist]
## Result: [1, 2, 3, 2, 4, 6, 3, 6, 9]
2. Generator Expressions for Memory Efficiency
## Memory-efficient list generation
def large_data_generator(limit):
return (x**2 for x in range(limit))
## Convert generator to list when needed
squared_numbers = list(large_data_generator(1000000))
Advanced Functional Techniques
import itertools
## Generating combinations
combinations = list(itertools.combinations([1, 2, 3, 4], 2))
## Result: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
## Cartesian product
cartesian_product = list(itertools.product([1, 2], [3, 4]))
## Result: [(1, 3), (1, 4), (2, 3), (2, 4)]
List Generation Workflow
graph TD
A[Input Data] --> B{List Generation Method}
B --> |Comprehension| C[Transformed List]
B --> |Generators| D[Memory-Efficient List]
B --> |Itertools| E[Complex Combinations]
Method |
Memory Usage |
Complexity |
Flexibility |
List Comprehension |
Moderate |
O(n) |
High |
Generator Expressions |
Low |
O(1) |
Moderate |
Itertools |
Varies |
O(n!) |
Very High |
Advanced LabEx Example
## Complex data processing in LabEx
def advanced_list_generator(data):
## Multiple transformations
return [
x * 2
for x in data
if x % 2 == 0 and x > 10
]
sample_data = range(1, 20)
processed_list = advanced_list_generator(sample_data)
## Result: [12, 14, 16, 18]
Recursive List Generation
def recursive_list_generator(n):
if n <= 0:
return []
return [n] + recursive_list_generator(n - 1)
## Generate descending list
descending_list = recursive_list_generator(5)
## Result: [5, 4, 3, 2, 1]
- Use generators for large datasets
- Leverage itertools for complex combinations
- Prefer list comprehensions for simple transformations
- Consider memory constraints
Error Handling in List Generation
def safe_list_generator(items):
try:
return [
int(x)
for x in items
if x.strip()
]
except ValueError:
return []
## Safe conversion
mixed_data = ['1', '2', 'three', '4']
safe_list = safe_list_generator(mixed_data)
## Result: [1, 2, 4]
By mastering these advanced list generation techniques, you'll become a more sophisticated Python programmer, capable of handling complex data manipulation tasks efficiently.