Published on

Python List Comprehensions - Write Less, Do More

Authors

Introduction

List comprehensions are one of Python's most Pythonic features. They let you create, filter, and transform lists in a single readable line — replacing multiple lines of for loops with elegant one-liners.

Master comprehensions and your code will be cleaner, faster, and more impressive.

Basic List Comprehension

The basic syntax is: [expression for item in iterable]

main.py
# Without comprehension
squares = []
for n in range(10):
    squares.append(n ** 2)

# With list comprehension ✅
squares = [n ** 2 for n in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Filtering with Conditions

Add an if clause to filter items: [expression for item in iterable if condition]

main.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Get only even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens)  # [2, 4, 6, 8, 10]

# Get words longer than 4 characters
words = ["cat", "python", "dog", "javascript", "hi"]
long_words = [w for w in words if len(w) > 4]
print(long_words)  # ['python', 'javascript']

if-else in Comprehensions

main.py
numbers = [1, 2, 3, 4, 5, 6]

# Label numbers as even or odd
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(labels)  # ['odd', 'even', 'odd', 'even', 'odd', 'even']

Note: when using if-else, put it before the for clause.

Nested List Comprehensions

main.py
# Flatten a 2D matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Multiplication table
table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in table:
    print(row)

Dictionary Comprehensions

main.py
# Basic dict comprehension
squares_dict = {n: n ** 2 for n in range(6)}
print(squares_dict)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Swap keys and values
original = {"a": 1, "b": 2, "c": 3}
swapped = {v: k for k, v in original.items()}
print(swapped)  # {1: 'a', 2: 'b', 3: 'c'}

# Filter a dictionary
prices = {"apple": 1.5, "banana": 0.5, "cherry": 3.0, "date": 5.0}
expensive = {k: v for k, v in prices.items() if v > 1}
print(expensive)  # {'apple': 1.5, 'cherry': 3.0, 'date': 5.0}

Set Comprehensions

main.py
# Get unique lengths of words
words = ["hello", "world", "hi", "python", "code", "hi"]
unique_lengths = {len(w) for w in words}
print(unique_lengths)  # {2, 4, 5, 6} — no duplicates!

Generator Expressions — Memory-Efficient Comprehensions

Generator expressions use () instead of []. They're lazy — they compute values one at a time instead of loading everything into memory.

main.py
# List comprehension — all values in memory at once
squares_list = [n ** 2 for n in range(1_000_000)]  # Uses lots of RAM

# Generator expression — computes one at a time
squares_gen = (n ** 2 for n in range(1_000_000))  # Uses minimal RAM

# Both work the same way
print(sum(squares_list))
print(sum(squares_gen))  # Same result, much less memory!

Use generators when dealing with large datasets.

Real-World Examples

Processing API responses:

main.py
users = [
    {"name": "Alice", "age": 28, "active": True},
    {"name": "Bob", "age": 16, "active": False},
    {"name": "Charlie", "age": 35, "active": True},
]

# Get names of active adult users
active_adults = [u["name"] for u in users if u["active"] and u["age"] >= 18]
print(active_adults)  # ['Alice', 'Charlie']

Parsing CSV-like data:

main.py
raw_data = "1,Alice,28\n2,Bob,16\n3,Charlie,35"

records = [
    {"id": int(p[0]), "name": p[1], "age": int(p[2])}
    for line in raw_data.strip().split("\n")
    if (p := line.split(","))  # Using walrus operator!
]
print(records)

File processing:

main.py
import os

# Get all Python files in a folder
py_files = [f for f in os.listdir(".") if f.endswith(".py")]

# Read and clean lines from a file
with open("data.txt") as f:
    clean_lines = [line.strip() for line in f if line.strip()]

When NOT to Use Comprehensions

main.py
# ❌ TOO complex — hard to read
result = [transform(item) for sublist in nested for item in sublist
          if condition1(item) if condition2(item)]

# ✅ Use a regular loop for complex logic
result = []
for sublist in nested:
    for item in sublist:
        if condition1(item) and condition2(item):
            result.append(transform(item))

Rule of thumb: If your comprehension doesn't fit on one readable line, use a regular loop.

Conclusion

List comprehensions are a cornerstone of Pythonic code. They're faster than equivalent for loops, more readable, and incredibly versatile. Practice them daily and they'll become second nature — a true sign of Python mastery.