Python18 min read

Python List Comprehension

Learn list comprehensions deeply: when to use them, how they work, and how to keep them readable.

Michael Brown
August 12, 2025
6.6k132

List comprehensions create lists in a compact, readable way. They are perfect when your logic is straightforward.

A list comprehension is basically:
- loop + optional filter + transform
- written in one line

## Basic example: squares

Loop version:

```python
squares = []
for i in range(5):
    squares.append(i ** 2)

print(squares)
```

Comprehension version:

```python
squares = [i ** 2 for i in range(5)]
print(squares)
```

Expected output:

```
[0, 1, 4, 9, 16]
```

## With a condition (filtering)

```python
evens = [i for i in range(10) if i % 2 == 0]
print(evens)
```

Expected output:

```
[0, 2, 4, 6, 8]
```

## Transform data (very common)

```python
cities = ["miami", "austin", "denver"]
upper_cities = [city.upper() for city in cities]
print(upper_cities)
```

Expected output:

```
['MIAMI', 'AUSTIN', 'DENVER']
```

## Nested comprehensions (use carefully)

```python
matrix = [[i * j for j in range(3)] for i in range(3)]
print(matrix)
```

Expected output:

```
[[0, 0, 0], [0, 1, 2], [0, 2, 4]]
```

## Graph: comprehension mental model

```mermaid
flowchart LR
  A[Iterable] --> B[Optional filter]
  B --> C[Transform]
  C --> D[New list]
```

Rule: if a comprehension becomes hard to read, use a normal loop. Readability matters more than “one line”.

In the next lesson, you will learn lambda functions and where they fit in real code.
#Python#Intermediate#Lists