Python List Comprehensions Explained
Ad
What are List Comprehensions?
List comprehensions are a concise way to create lists in a single readable line, replacing multi-line for loops.
Before and After
# Traditional loop
squares = []
for n in range(5):
squares.append(n ** 2)
# List comprehension — same result
squares = [n ** 2 for n in range(5)]
# [0, 1, 4, 9, 16]
Adding a Condition
evens = [n for n in range(10) if n % 2 == 0]
# [0, 2, 4, 6, 8]
The General Syntax
[expression for item in iterable if condition]
Dict and Set Comprehensions Too
squares = {n: n**2 for n in range(4)} # dict
unique = {c for c in "hello"} # set {'h','e','l','o'}
Real Example
users = [{"name": "Sara", "active": True}, {"name": "Ali", "active": False}]
active_names = [u["name"] for u in users if u["active"]]
# ['Sara']
FAQs
Are comprehensions faster than loops?
Usually slightly faster and always more readable for simple transforms. For complex logic, a regular loop is clearer.
Can I nest them?
Yes, but keep it readable. More in our Python section.
