A comprehension builds a list, dict or set in one line from a loop.
List comprehension
[expression for item in iterable]
squares = [n * n for n in range(1, 6)] → [1, 4, 9, 16, 25]
With a filter
[n for n in numbers if n % 2 == 0]
With if / else (transform)
["Pass" if m >= 40 else "Fail" for m in marks] — note the if/else comes before for.
Dictionary comprehension
{name: len(name) for name in names}
Set comprehension
{word.lower() for word in words}
Nested
[(r, c) for r in range(3) for c in range(3)] — flatten: [x for row in matrix for x in row]
Generator expression
sum(n * n for n in range(1_000_000)) — round brackets, no list in memory.
Keep it readable: if a comprehension needs more than one condition or gets long, use a normal loop.
Example
marks = {"Asha": 88, "Ravi": 35, "Neha": 72, "Amit": 39}
passed = [name for name, m in marks.items() if m >= 40]
print("Passed:", passed)
results = {name: ("Pass" if m >= 40 else "Fail") for name, m in marks.items()}
print(results)
prices = ["₹120", "₹45", "₹300"]
numbers = [int(p.replace("₹", "")) for p in prices]
print(numbers, sum(numbers))
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [x for row in matrix for x in row]
print(flat)
print(sum(n * n for n in range(1, 11)))
Output: Passed: ['Asha', 'Neha'], a dict of Pass/Fail per student, [120, 45, 300] 465, [1, 2, 3, 4, 5, 6], and 385.