agyanadda@gmail.com

Python List and Dictionary Comprehensions

Python Data Structures 1 min read Updated Dec 4, 2026 Topic 16 of 32

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

Example — Comprehensions in practice Python
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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does [n * 2 for n in range(3)] return?

Exercise 2 True / False

A generator expression uses round brackets and does not build a full list in memory.

Exercise 3 Fill in the Blank

Filter items: [x for x in nums ___ x > 0]

Frequently Asked Questions

Usually a little faster for building lists, and shorter. But readability matters more: if the logic is complex, a regular for loop is the better choice.