Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 1 of 13

List comprehensions

Building a new list from an iterable in a single expression: the [expression for item in iterable] form, how it compares to a for loop with append, and when a comprehension improves readability.

Beginner 10 min read·Lesson 145 of 306 in Python Programming

Learning objectives

  • Write list comprehensions that transform every item
  • Convert between a for-append loop and a comprehension
  • Judge when a comprehension is clearer than a loop

Definition

A list comprehension is an expression of the form [expression for item in iterable] that evaluates the expression for each item and collects the results into a new list.

Introduction

A very common loop pattern creates an empty list and appends a transformed value for each item. List comprehensions express that whole pattern in one readable line: squares = [n * n for n in range(5)].

Read it from the middle outwards: for n in range(5), compute n * n, and collect the results in a list.

Why it matters

Comprehensions are one of the most characteristic features of Python; you'll see them in almost every real codebase. They are shorter than the equivalent loop, avoid off-by-one mistakes with indexes and usually run a little faster.

Detailed explanation

The general form is [expression for name in iterable]. The expression can use name and anything else in scope, including function calls and conditional expressions.

It always produces a new list; the original iterable is not changed. The new list has exactly one element per item processed.

Any iterable works as the source: lists, strings, ranges, dictionary views, files and generators.

The loop variable lives only inside the comprehension; it doesn't leak into the surrounding code.

A comprehension is equivalent to: result = []; for name in iterable: result.append(expression). If you need several statements per item, print debugging, or early exits with break, use a normal loop instead.

Keep comprehensions short — if one spans more than a line or two, a loop or a helper function is clearer.

Syntax

Python
new_list = [expression for item in iterable]
# equivalent loop
new_list = []
for item in iterable:
new_list.append(expression)
  • Produces a new list.
  • One result per item.
  • The loop variable doesn't leak.

Code examples

Transforming every item

Python
numbers = [1, 2, 3, 4, 5]
squares = [n * n for n in numbers]
print(squares)
names = ["asha", "ravi", "meera"]
print([name.title() for name in names])
print([len(name) for name in names])
Output
[1, 4, 9, 16, 25]
['Asha', 'Ravi', 'Meera']
[4, 4, 5]

Loop versus comprehension

Python
prices = [100, 250, 80]
with_tax = []
for p in prices:
with_tax.append(round(p * 1.18, 2))
print(with_tax)
print([round(p * 1.18, 2) for p in prices])
Output
[118.0, 295.0, 94.4]
[118.0, 295.0, 94.4]

More examples

Comprehensions over different iterables

Python
word = "Python"
print([ch.upper() for ch in word])
print([i * 10 for i in range(1, 6)])
marks = {"Asha": 91, "Ravi": 74}
print([f"{name}={score}" for name, score in marks.items()])
rows = ["12, 5", "7, 3", "20, 1"]
products = [int(a) * int(b) for a, b in (row.split(",") for row in rows)]
print(products)
Output
['P', 'Y', 'T', 'H', 'O', 'N']
[10, 20, 30, 40, 50]
['Asha=91', 'Ravi=74']
[60, 21, 20]

Step-by-step explanation

  • Iterating a string visits each character.
  • range(1, 6) supplies the numbers 1 to 5.
  • items() yields (key, value) pairs, unpacked into name and score.
  • The last comprehension iterates over a generator that splits each row; int() also ignores the space after the comma.

Expected output

Running “Comprehensions over different iterables” prints exactly:

TextOutput
['P', 'Y', 'T', 'H', 'O', 'N']
[10, 20, 30, 40, 50]
['Asha=91', 'Ravi=74']
[60, 21, 20]

Practical applications

  • Cleaning a column of data: [s.strip().lower() for s in raw].
  • Extracting a field from records: [user['email'] for user in users].
  • Converting types: [int(x) for x in line.split()].

Best practices

  • Use comprehensions for simple transformations and filters.
  • Name the loop variable meaningfully.
  • Switch to a loop when logic needs more than one expression.

Common mistakes

Comprehension for side effects

Avoid

[print(x) for x in items]

Prefer

for x in items:
print(x)

A comprehension builds a list; using it only for side effects creates a useless list of None values.

Over-long comprehension

Avoid

[f(g(x), h(y)) for x in a if p(x) for y in b if q(x, y)]

Prefer

Use a loop or helper functions.

Readability comes first; complex logic belongs in a regular loop.

Important notes

  • Comprehensions are typically slightly faster than append loops because the list-building happens inside the interpreter.

Key takeaways

  • [expr for x in iterable] builds a new list.
  • It replaces the empty-list-and-append pattern.
  • Use loops for side effects or complex logic.

Try it yourself

  1. 1
    Convert a list of Celsius temperatures to Fahrenheit with a comprehension.
  2. 2
    Build a list of the first letters of each word in a sentence.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic