List Comprehension
Introduction to List Comprehension
List comprehension is a concise and powerful way to create lists in Python, allowing you to generate, transform, and filter lists in a single line of code.
Basic Syntax
## Basic list comprehension structure
new_list = [expression for item in iterable]
## Example: Creating a list of squares
squares = [x**2 for x in range(10)]
## Result: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Comprehension Types
## Converting strings to uppercase
names = ['alice', 'bob', 'charlie']
uppercase_names = [name.upper() for name in names]
## Result: ['ALICE', 'BOB', 'CHARLIE']
2. Filtering with Conditional
## Filtering even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
## Result: [2, 4, 6, 8, 10]
## Nested conditions
result = [x*y for x in range(3) for y in range(3) if x != y]
## Equivalent to nested loops with condition
Comparison with Traditional Methods
Method |
Readability |
Performance |
Complexity |
List Comprehension |
High |
Fast |
Simple |
Traditional Loop |
Medium |
Slower |
More Verbose |
map() Function |
Low |
Moderate |
Complex |
Advanced Comprehension Techniques
Nested List Comprehension
## Creating a 3x3 matrix
matrix = [[i*j for j in range(3)] for i in range(3)]
## Result: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Conditional Expressions
## Ternary operation in comprehension
numbers = [1, 2, 3, 4, 5]
classified = ['even' if num % 2 == 0 else 'odd' for num in numbers]
## Result: ['odd', 'even', 'odd', 'even', 'odd']
List Comprehension Workflow
graph TD
A[Input Iterable] --> B{Condition}
B -->|Pass| C[Apply Transformation]
B -->|Fail| D[Skip Item]
C --> E[Create New List]
## Benchmark: List Comprehension vs Traditional Loop
import timeit
## List comprehension
def comp_method():
return [x**2 for x in range(1000)]
## Traditional loop
def loop_method():
result = []
for x in range(1000):
result.append(x**2)
return result
Best Practices
- Use list comprehension for simple transformations
- Avoid complex logic within comprehensions
- Prioritize readability
- Consider generator expressions for large datasets
Common Pitfalls
- Don't sacrifice readability for brevity
- Be cautious with complex nested comprehensions
- Memory usage can be high for large lists
Key Takeaways
- List comprehensions provide a concise way to create lists
- They combine iteration, transformation, and filtering
- Useful for data manipulation and transformation tasks
LabEx recommends practicing list comprehensions to write more Pythonic code.