List Manipulation Tricks
List Comprehensions
## Basic list comprehension
squares = [x**2 for x in range(10)]
print(squares) ## Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
## Conditional list comprehension
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) ## Output: [0, 4, 16, 36, 64]
## Filtering with multiple conditions
words = ['hello', 'world', 'python', 'programming']
long_words = [word.upper() for word in words if len(word) > 5]
print(long_words) ## Output: ['PYTHON', 'PROGRAMMING']
List Manipulation Techniques
Flattening Nested Lists
## Nested list flattening
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in nested_list for item in sublist]
print(flattened) ## Output: [1, 2, 3, 4, 5, 6]
Zipping Lists
## Combining multiple lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined) ## Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
List Manipulation Workflow
graph TD
A[Original List] --> B{Manipulation Technique}
B -->|Comprehension| C[Transform Elements]
B -->|Filtering| D[Select Specific Elements]
B -->|Zipping| E[Combine Multiple Lists]
B -->|Flattening| F[Reduce Nested Structures]
Advanced Tricks
Unpacking and Multiple Assignment
## List unpacking
first, *rest, last = [1, 2, 3, 4, 5]
print(first) ## Output: 1
print(rest) ## Output: [2, 3, 4]
print(last) ## Output: 5
List Manipulation Comparison
Technique |
Purpose |
Complexity |
Comprehension |
Transform/Filter |
Low |
Zip |
Combine Lists |
Low |
Unpacking |
Flexible Assignment |
Medium |
Nested List Manipulation |
Complex Transformations |
High |
## Comparing list manipulation methods
import timeit
## List comprehension
comprehension_time = timeit.timeit('[x**2 for x in range(1000)]', number=1000)
## Traditional loop
loop_time = timeit.timeit('''
squares = []
for x in range(1000):
squares.append(x**2)
''', number=1000)
print(f"Comprehension Time: {comprehension_time}")
print(f"Loop Time: {loop_time}")
Key Takeaways
- List comprehensions provide concise and powerful list manipulation
- Advanced techniques can simplify complex list operations
- Consider performance when choosing manipulation method
- Practice and experiment with different approaches
LabEx recommends mastering these list manipulation tricks to write more efficient Python code.