October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

A Practical Guide to List Comprehensions in Python

How to read and write Python list comprehensions: clause order, filters, nesting, scope, generator expressions, async use, and when to prefer a loop.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A list comprehension builds a new list from an expression and at least one for clause, with optional if clauses that filter. [x * x for x in range(5)] gives [0, 1, 4, 9, 16]. This guide covers how to read the clauses in order, how scope works, when a generator expression or plain loop is the better choice, and where the async variants fit.

The basic shape

The pattern is [expression for item in iterable]. The expression is evaluated once per iteration and the results are collected into a list, as described in the Python language reference.

squares = [x * x for x in range(5)]
# [0, 1, 4, 9, 16]

Filtering with if

An if clause excludes iterations where the condition is false. The result expression is evaluated only for iterations that pass.

names = ["  Ada ", "", "Grace"]
cleaned = [name.strip() for name in names if name]
# ['Ada', 'Grace']

Reading multiple clauses

Read clauses left to right as nested blocks: each later for runs inside the earlier one, and an if applies at its position in the sequence.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
pairs = [(x, y) for x in xs for y in ys]

# equivalent to:
pairs = []
for x in xs:
    for y in ys:
        pairs.append((x, y))

Without filters, you get one pair per combination. Note the parentheses around (x, y): when the result expression is a tuple, they are required to avoid ambiguity (see the Functional Programming HOWTO).

Scope: what does and does not leak

  • The loop variable of a comprehension does not leak into the surrounding scope. This differs from Python 2 behavior, which should not be taught as current.
  • The iterable in the first for clause is evaluated in the enclosing scope. The rest of the comprehension runs in an implicit nested scope.

Both points come from the language reference.

Nested comprehensions

Brackets inside the result expression build an inner list for every outer iteration. The official tutorial transposes a matrix this way:

[[row[i] for row in matrix] for i in range(4)]

For this specific job, the built-in zip(*matrix) is an alternative: use list(zip(*matrix)) if you need a list, or iterate over zip(*matrix) directly. Whichever form makes the data flow easiest to follow is the better one.

List comprehension or generator expression?

Axis List comprehension Generator expression
Syntax [f(x) for x in data] (f(x) for x in data)
Result A list, fully built in memory An iterator
Evaluation Eager Lazy, computed as needed
Good fit You need the whole list, indexing, or repeated passes Very large or infinite input consumed incrementally

The HOWTO puts it this way: “Generator expressions return an iterator that computes the values as necessary, not needing to materialize all the values at once.” A list comprehension is never lazy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When to use a loop instead

A comprehension suits an expression and iteration that fit on one readable line or a short wrapped expression. Switch to an ordinary loop when the body needs several steps, error handling, side effects, or intermediate names that explain the process. This is a readability judgment drawn from the documented semantics, not a benchmark result. The sources reviewed do not establish that comprehensions are universally faster or clearer, so choose by readability for your audience.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Asynchronous comprehensions

Inside an async def, comprehensions can use asynchronous iteration and await, which may suspend the coroutine. The language reference records asynchronous comprehensions as added in Python 3.6, and nested asynchronous comprehensions inside async functions as allowed from Python 3.11. Check your project’s minimum supported Python version before relying on them.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.