Python5 min read
Python List Comprehension
Create lists efficiently using list comprehensions.
Michael Brown
December 18, 2025
0.0k0
Create lists in one line.
Basic List Comprehension
```python # Old way squares = [] for i in range(5): squares.append(i ** 2)
New way (list comprehension) squares = [i ** 2 for i in range(5)] print(squares) # [0, 1, 4, 9, 16] ```
With Condition
```python # Get even numbers evens = [i for i in range(10) if i % 2 == 0] print(evens) # [0, 2, 4, 6, 8]
Get names starting with 'A' names = ["Alice", "Bob", "Anna", "Charlie"] a_names = [name for name in names if name.startswith("A")] print(a_names) # ['Alice', 'Anna'] ```
Transform Data
```python cities = ["miami", "austin", "denver"] upper_cities = [city.upper() for city in cities] print(upper_cities) # ['MIAMI', 'AUSTIN', 'DENVER'] ```
Nested Comprehension
```python # Create 2D list matrix = [[i * j for j in range(3)] for i in range(3)] print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]] ```
Remember
- More readable for simple cases - Faster than loops - Don't overuse - keep it simple
#Python#Intermediate#Lists