List Comprehension Python: Write Concise Code

A Python list comprehension builds a new list from an iterable in one expression. Put the output expression first, then the for clause, and add an if clause when items need filtering.

Start with the smallest list comprehension

Use a comprehension when every input item becomes one output item. The expression num ** 2 runs once for each value in numbers.

numbers = [1, 2, 3, 4, 5]
squares = [num ** 2 for num in numbers]
print(squares)
[1, 4, 9, 16, 25]

Filter items with an if clause

Put the filter after the for clause to omit items before they reach the expression.

numbers = range(10)
even = [num for num in numbers if num % 2 == 0]
print(even)
[0, 2, 4, 6, 8]

Transform and filter together

The filter can protect a conversion or other operation that should run only for accepted values. Here int runs only after isdigit returns true.

values = ["42", "skip", "17"]
parsed = [int(value) for value in values if value.isdigit()]
print(parsed)
[42, 17]

Use if and else to keep every item

An if expression before the for clause changes the output without removing an input item. This is different from the filter form, which reduces the list length.

numbers = [1, 2, 3, 4]
labels = ["even" if num % 2 == 0 else "odd" for num in numbers]
print(labels)
['odd', 'even', 'odd', 'even']

Flatten a nested list

Two for clauses read like nested loops. The outer clause selects each row, and the inner clause emits each item from that row.

rows = [[1, 2], [3, 4]]
flattened = [item for row in rows for item in row]
print(flattened)
[1, 2, 3, 4]

When a loop is clearer

Use a regular for loop when the expression needs several branches, side effects, or multiple statements. Short code is useful only when the evaluation order remains easy to read.

  • Expression first: what goes into the new list.
  • for clause next: where each input comes from.
  • if clause last: which inputs survive.
  • if/else expression before for: how each input is transformed.

Reference

Python list comprehensions documentation

Ninad
Ninad

A Python and PHP developer turned writer out of passion. Over the last 6+ years, he has written for brands including DigitalOcean, DreamHost, Hostinger, and many others. When not working, you'll find him tinkering with open-source projects, vibe coding, or on a mountain trail, completely disconnected from tech.

Articles: 136