List comprehension
Builds a new list by transforming and optionally filtering items.
[expression for item in iterable if condition]This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Builds a new list by transforming and optionally filtering items.
List comprehensions provide a concise and performant syntactic construct for creating lists from iterables. From a technical standpoint, they are generally faster than equivalent 'for' loops utilizing the '.append()' method because the list construction is performed at the bytecode level in C. However, list comprehensions are 'eager' expressions, meaning they instantiate the entire list in memory immediately. For extremely large datasets, this can lead to excessive memory consumption or a MemoryError; in such scenarios, a generator expression is preferred for lazy evaluation. When processing dates within a comprehension, it is recommended to use ISO 8601 strings or timestamp integers to ensure reliable ordering and comparison, as locale-dependent strings can lead to inconsistent logical results. While powerful, list comprehensions should remain simple to adhere to PEP 8 readability standards.
Quick reference
Syntax
[expression for item in iterable if condition]
Inputs
Parameters
See it in practice
Examples
Basic Transformation
numbers = [1, 2, 3, 4, 5]
squares = [n**2 for n in numbers][1, 4, 9, 16, 25]
Squares each integer in the source list using a compact expression.
Filtering with Conditions
data = [12, 45, 7, 23, 10, 56]
filtered = [x for x in data if x > 20][45, 23, 56]
Filters the list to include only elements that satisfy the predicate condition.
Date Filtering and Sorting
dates = ['2023-05-01', '2021-12-15', '2023-10-20']
recent = sorted([d for d in dates if d >= '2023-01-01'])['2023-05-01', '2023-10-20']
Filters a list of ISO date strings. ISO strings are used to ensure reliable lexicographical comparison.
Debug faster
Common Errors
SyntaxError
Cause: Attempting to use an 'if-else' conditional at the end of the comprehension where only a filter is allowed.
Fix: Move the 'if-else' block to the expression position at the start of the comprehension.
[x for x in range(5) if x > 2 else 0]MemoryError
Cause: Creating a list comprehension over a massive range or infinite stream, exhausting available system RAM.
Fix: Use a generator expression (using parentheses instead of brackets) for lazy evaluation.
[x * 2 for x in range(10**12)]Runtime support
Compatibility
Works in all Python 3.x (syntax is older than 3.8)
Source: MDN Web Docs
Common questions
Frequently Asked Questions
Builds a new list by transforming and optionally filtering items.
expression: Value to put into the new list. iterable: Source items to loop over. condition: Optional filter condition.
SyntaxError: Move the 'if-else' block to the expression position at the start of the comprehension. MemoryError: Use a generator expression (using parentheses instead of brackets) for lazy evaluation.