Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to Python

Python List Comprehensions and Generators

PythonBy Muhammad Fareed
pythonlist-comprehensionsgeneratorsadvanced

Short answer: a list comprehension is a compact way to build a list from another iterable in a single line: [expression for item in iterable if condition]. It replaces many short for loops that append to a list.

Loop vs list comprehension

# Using a loop
squares = []
for n in range(5):
    squares.append(n * n)

# Using a list comprehension
squares = [n * n for n in range(5)]

print(squares)  # [0, 1, 4, 9, 16]

Both produce the same list. The comprehension is shorter and usually a little faster, because the appending happens in optimized code.

Syntax

[expression for item in iterable]
[expression for item in iterable if condition]
  • expression: what to put in the new list for each item.
  • item in iterable: the loop.
  • condition (optional): keeps only items where it is true.

Filtering

numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)  # [2, 4, 6]

Transforming and filtering together

names = ["asha", "ravi", "", "meera"]
clean = [name.title() for name in names if name]
print(clean)  # ['Asha', 'Ravi', 'Meera']

if / else inside the expression

When you want a value for every item, put the conditional before the for:

labels = ["even" if n % 2 == 0 else "odd" for n in range(5)]
print(labels)  # ['even', 'odd', 'even', 'odd', 'even']

A trailing if (after the loop) filters. A conditional expression (before the loop) chooses a value. Mixing these up is the most common error.

Nested loops

pairs = [(x, y) for x in range(3) for y in range(2)]
print(pairs)  # [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]

matrix = [[1, 2], [3, 4], [5, 6]]
flat = [value for row in matrix for value in row]
print(flat)  # [1, 2, 3, 4, 5, 6]

Read nested comprehensions left to right, in the same order as the equivalent nested for loops.

Dictionary and set comprehensions

word_lengths = {word: len(word) for word in ["apple", "fig", "banana"]}
print(word_lengths)  # {'apple': 5, 'fig': 3, 'banana': 6}

unique_lengths = {len(word) for word in ["apple", "fig", "pear"]}
print(unique_lengths)  # {3, 4, 5}

Comprehension or generator expression?

A list comprehension builds the whole list in memory. If you only loop over the result once, or the data is large, use a generator expression with parentheses:

total = sum(n * n for n in range(1_000_000))

This produces values one at a time and uses almost no extra memory. Learn more in generators and iterators.

When not to use a comprehension

  • The logic needs several statements or is hard to read in one line.
  • You are using it only for side effects such as print; use a normal loop.
  • Deeply nested comprehensions: more than two loops usually hurt readability.

Common mistakes

  • Forgetting that the variable inside a comprehension does not leak into the surrounding scope in Python 3.
  • Building a huge list when a generator would do.
  • Using if and else in the wrong position, as shown above.

FAQs

Are list comprehensions faster than loops?

Usually somewhat faster for building lists, but readability matters more than the small gain.

Can I use a function inside a comprehension?

Yes, for example [clean(x) for x in data]. The function is called once per item.

What is the difference between map/filter and a comprehension?

They do similar work. Most Python code prefers comprehensions because they are easier to read.

How do I handle errors inside a comprehension?

Move the logic into a helper function that catches the error, then call that function in the comprehension. See handling exceptions in Python.