prices =[10,25,50,75,100]
affordable =[p for p in prices if p <=50]print(affordable)
squares =[n **2for n inrange(1,6)]print(squares)
Output
[10, 25, 50]
[1, 4, 9, 16, 25]
Note Comprehensions are more Pythonic and faster than equivalent for-loop-with-append patterns. Keep them simple; if nesting gets deep, use a regular loop.
# Transform + filter
temps_f =[32,68,95,104,50]
warm_c =[(f -32)*5/9for f in temps_f if f >60]print([round(c,1)for c in warm_c])# Nested comprehension (flatten)
matrix =[[1,2],[3,4],[5,6]]
flat =[n for row in matrix for n in row]print(flat)
Output
[20.0, 35.0, 40.0]
[1, 2, 3, 4, 5, 6]
Note In nested comprehensions, the outer loop comes first: [x for row in matrix for x in row]. This matches the order of equivalent nested for loops.
Frequently asked questions
How do you list comprehension?
Python covers this with 2 copy-ready snippets on this page. The "List Comprehensions" snippet in Python uses `[expression for item in iterable if condition]`.
Which code does the Python example use?
The "List Comprehensions" snippet uses `[expression for item in iterable if condition]`, from the Lists section of the Python cheat sheet.
What other Python snippets are shown for "list comprehension"?
Besides "List Comprehensions", this page also shows "List Comprehensions (Detailed)".
Is there anything to watch out for?
Yes. For "List Comprehensions": Comprehensions are more Pythonic and faster than equivalent for-loop-with-append patterns. Keep them simple; if nesting gets deep, use a regular loop.