Python’s list comprehension is a concise way to create lists by applying an expression to each item in an iterable, optionally filtering elements with a condition—all in a single, readable line.
Basic Syntax
[expression for item in iterable if condition]
expression — what you want to produce for each item (can be just the item itself or a transformed version)
item — a variable representing each element from the iterable
iterable — any sequence or iterable (like a list, range, string, etc.)
if condition — optional filter to include only items that satisfy the condition
Example 1: Square numbers from 0 to 4
squares = [x**2 for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]
Example 2: Filter even numbers and double them
evens_doubled = [x * 2 for x in range(10) if x % 2 == 0]
print(evens_doubled) # Output: [0, 4, 8, 12, 16]
How it works:
Iterates over each element in iterable.
Applies the optional if condition to filter elements.
Evaluates the expression for each filtered element.
Collects all results into a new list.
Benefits
More concise and readable than using loops to build lists.
Often faster than equivalent for loops in Python due to internal optimizations.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Python’s list comprehension is a concise way to create lists by applying an expression to each item in an iterable, optionally filtering elements with a condition—all in a single, readable line.
Basic Syntax
expression— what you want to produce for each item (can be just the item itself or a transformed version)item— a variable representing each element from the iterableiterable— any sequence or iterable (like a list, range, string, etc.)if condition— optional filter to include only items that satisfy the conditionExample 1: Square numbers from 0 to 4
Example 2: Filter even numbers and double them
How it works:
iterable.ifcondition to filter elements.expressionfor each filtered element.Benefits
forloops in Python due to internal optimizations.