List Comprehension
Introduction to List Comprehension
List comprehension is a concise and powerful way to create lists in Python, providing a compact alternative to traditional loop-based list generation.
Basic Syntax
## Basic list comprehension structure
## [expression for item in iterable]
## Simple example
numbers = [x for x in range(10)]
## Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Comprehension Types
flowchart TD
A[List Comprehension] --> B[Basic]
A --> C[Conditional]
A --> D[Nested]
A --> E[Complex]
Conditional List Comprehension
## Filtering with conditions
even_numbers = [x for x in range(10) if x % 2 == 0]
## Result: [0, 2, 4, 6, 8]
## Multiple conditions
filtered_numbers = [x for x in range(20) if x % 2 == 0 if x % 3 == 0]
## Result: [0, 6, 12, 18]
Nested List Comprehension
## Creating a matrix
matrix = [[x*y for x in range(3)] for y in range(3)]
## Result: [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Comparison with Traditional Methods
Method |
Readability |
Performance |
Complexity |
List Comprehension |
High |
Faster |
Simple |
Traditional Loop |
Medium |
Slower |
More Verbose |
Map/Filter |
Low |
Moderate |
Complex |
Advanced Examples
## Transforming strings
words = ['hello', 'world', 'python']
uppercase_words = [word.upper() for word in words]
## Result: ['HELLO', 'WORLD', 'PYTHON']
## Flattening nested lists
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = [num for sublist in nested_list for num in sublist]
## Result: [1, 2, 3, 4, 5, 6]
## Comparing comprehension with loop
## List comprehension
squares_comp = [x**2 for x in range(1000)]
## Traditional loop
squares_loop = []
for x in range(1000):
squares_loop.append(x**2)
Best Practices
- Use list comprehension for simple transformations
- Keep comprehensions readable
- Avoid complex nested comprehensions
- Consider readability over brevity
LabEx recommends mastering list comprehension as a key Python skill for writing concise and efficient code.