List Comprehension Techniques
Introduction to List Comprehensions
List comprehensions provide a concise way to create lists in Python, combining iteration and conditional logic in a single line of code.
Basic List Comprehension Syntax
## Basic syntax
## [expression for item in iterable]
## Simple example
squares = [x**2 for x in range(10)]
print(squares) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Conditional List Comprehensions
## Filtering with conditions
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) ## [0, 4, 16, 36, 64]
Advanced Comprehension Techniques
Multiple Conditions
## Complex filtering
filtered_numbers = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]
print(filtered_numbers) ## [0, 6, 12, 18]
Nested List Comprehensions
## Creating nested lists
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix) ## [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Comprehension Types
graph TD
A[Comprehension Types] --> B[List Comprehension]
A --> C[Set Comprehension]
A --> D[Dict Comprehension]
A --> E[Generator Expression]
Practical Examples
String Manipulation
## Converting strings
words = ['hello', 'world', 'python']
uppercase_words = [word.upper() for word in words]
print(uppercase_words) ## ['HELLO', 'WORLD', 'PYTHON']
Method |
Readability |
Performance |
Complexity |
Traditional Loop |
Medium |
Slower |
More Lines |
List Comprehension |
High |
Faster |
Compact |
Advanced Use Cases
Flattening Lists
## Flattening nested lists
nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for sublist in nested for num in sublist]
print(flattened) ## [1, 2, 3, 4, 5, 6, 7, 8, 9]
Common Pitfalls
- Avoid overly complex comprehensions
- Prioritize readability
- Use traditional loops for complex logic
Best Practices
- Use list comprehensions for simple transformations
- Keep comprehensions readable
- Break complex comprehensions into multiple lines
LabEx recommends mastering list comprehensions to write more pythonic and efficient code.