Iteration Techniques
Comprehensions: Powerful Iteration Shortcuts
List Comprehensions
Concise way to create lists with inline iteration:
## Basic list comprehension
squares = [x**2 for x in range(10)]
print(squares) ## [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) ## [0, 4, 16, 36, 64]
Dictionary Comprehensions
Create dictionaries dynamically:
## Dictionary from keys and values
names = ['Alice', 'Bob', 'Charlie']
name_lengths = {name: len(name) for name in names}
print(name_lengths) ## {'Alice': 5, 'Bob': 3, 'Charlie': 7}
Set Comprehensions
Generate sets with compact syntax:
unique_squares = {x**2 for x in range(10)}
print(unique_squares)
Advanced Iteration Methods
enumerate()
Function
Iterate with index and value:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
zip()
Function
Combine multiple iterables:
names = ['Alice', 'Bob']
ages = [25, 30]
zipped = list(zip(names, ages))
print(zipped) ## [('Alice', 25), ('Bob', 30)]
Generator Expressions
Memory-efficient iteration:
## Generator expression
gen = (x**2 for x in range(10))
print(list(gen)) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Iteration Control Techniques
Powerful iteration tools:
import itertools
## Infinite cycling
colors = ['red', 'green', 'blue']
cycle_colors = itertools.cycle(colors)
## Take first 10 cycled colors
first_10 = list(itertools.islice(cycle_colors, 10))
print(first_10)
Technique |
Memory Efficiency |
Readability |
Performance |
List Comprehension |
Moderate |
High |
Fast |
Generator Expression |
Excellent |
High |
Efficient |
Traditional Loop |
Good |
Moderate |
Standard |
Key Iteration Patterns
graph TD
A[Iteration Techniques] --> B[Comprehensions]
A --> C[Advanced Methods]
A --> D[Control Techniques]
B --> E[List Comprehension]
B --> F[Dict Comprehension]
B --> G[Set Comprehension]
C --> H[enumerate]
C --> I[zip]
D --> J[itertools]
Best Practices
- Use comprehensions for simple transformations
- Prefer generator expressions for large datasets
- Leverage
itertools
for complex iteration scenarios
- LabEx recommends mastering these techniques for efficient Python programming