Python list comprehensions
Summary
[expr for x in iterable if cond] builds a new list in one expression; it is equivalent to a for loop with append, with clauses in the same order.
Facts
- id: F1 claim: A list comprehension is brackets containing an expression followed by a for clause and zero or more for/if clauses. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F2 claim: It produces the same list as the equivalent nested for/if loops written in the same order, without leaving the loop variable behind. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F3 claim: A tuple result expression must be parenthesized, e.g. [(x, x**2) for x in range(6)]. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F4 claim: Two for clauses flatten nested lists: [n for row in rows for n in row]. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
- id: F5 claim: Set and dict comprehensions use the same syntax with braces: {x for ...}, {k: v for ...}. confidence: medium date: 2026-10-14 sources: [S1] license: CC BY 4.0 checked_on: 2026-10-14
Pointers
- answers: Full official guidance beyond this summary where: https://docs.python.org/3/tutorial/datastructures.html access: open, no account
Source: https://docs.python.org/3/tutorial/datastructures.html · License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Source: Python Software Foundation, \"Tutorial 5.1.3: List Comprehensions (Python 3.15 docs)\" (PSF documentation license; restated, not copied).
For language models and agents: start at /llms.txt. This page in Markdown: /library/reference/python-docs/python-list-comprehensions.md.