⚡0 XP🔥0

List, Dict & Set Comprehensions

Lesson 29 of 33 ⏱ 5 min read ✎ 4 exercises ❓ 5-question quiz ▶ Runs Python

Build lists, dictionaries and sets in one readable line - with conditions, if-else, nested loops, and when NOT to use comprehensions.

What is a comprehension?#

A comprehension is a short, readable way to create a new list, dict or set from an existing sequence - in one line.

Without a comprehension:

squares = []
for n in range(1, 6):
    squares.append(n * n)

With a list comprehension:

squares = [n * n for n in range(1, 6)]

Both give [1, 4, 9, 16, 25].

Basic syntax#

[expression for item in iterable]

Read it as: "give me expression for each item in iterable".

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

List comprehension को एक वाक्य की तरह पढ़ें:

[n * n for n in range(1, 6)] → "1 से 5 तक हर n के लिए, n * n दो।"

इसमें तीन हिस्से हैं:

  1. क्या चाहिए - n * n (हर item पर क्या करना है)
  2. किस पर loop - for n in range(1, 6)
  3. (वैकल्पिक) शर्त - if ... (कौन-से items रखने हैं)

यह 3-4 लाइन के for loop + append का छोटा और तेज़ रूप है।

Filtering with if#

Add if condition at the end to keep only some items:

[expression for item in iterable if condition]
▶ Try it YourselfPython
Ctrl + Enter to run

Choosing values with if-else#

To transform every item into one of two values, put if-else before for:

[value_if_true if condition else value_if_false for item in iterable]
▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

Position matters:

  • Filter (drop items): [x for x in data if x > 0] - if at the end, no else.
  • Choose (keep all items): [x if x > 0 else 0 for x in data] - if-else before for.

[x for x in data if x > 0 else 0] is a SyntaxError.

Nested loops in a comprehension#

The for clauses are written in the same order as nested loops:

▶ Try it YourselfPython
Ctrl + Enter to run

Dictionary comprehensions#

{key_expr: value_expr for item in iterable}
▶ Try it YourselfPython
Ctrl + Enter to run

Set comprehensions#

▶ Try it YourselfPython
Ctrl + Enter to run

Generator expressions#

Using round brackets creates a generator - it produces values one at a time instead of building a whole list in memory. Great with sum, max, any, all:

▶ Try it YourselfPython
Ctrl + Enter to run

You'll learn more about generators in the next lesson.

When NOT to use comprehensions#

Comprehensions are great for simple transformations. If it needs several conditions, nested if-else, or side effects (printing, writing files), use a normal loop:

# Hard to read - avoid
result = [x * 2 if x > 0 else x * -1 if x < -10 else 0 for x in data if x != 5]

# Not for side effects - avoid
[print(x) for x in data]     # use a for loop instead
Tip

Rule of thumb: if the comprehension doesn't fit comfortably on one line, or you have to read it twice, write a regular loop.

Summary#

  • [expr for x in items] - build a list in one line.
  • [expr for x in items if cond] - filter items.
  • [a if cond else b for x in items] - choose a value for every item.
  • {k: v for ...} → dict; {expr for ...} → set; (expr for ...) → generator.
  • Keep comprehensions short and simple; use loops for complex logic.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Even squares

Using one list comprehension, create result - the squares of the even numbers from 1 to 20 - and print it.

Expected output:
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
2

Pass or fail labels

Using a comprehension with if-else, create labels where each mark becomes "Pass" (>= 33) or "Fail", and print it.

Expected output:
['Pass', 'Fail', 'Pass', 'Pass', 'Fail']
3

Name lengths dictionary

Create a dict comprehension lengths mapping each name (in title case) to its length, but only for names longer than 3 letters. Print it.

Expected output:
{'Asha': 4, 'Ravi': 4, 'Neha': 4, 'Karan': 5}
4

Flatten a matrix

Flatten the 2D list matrix into a single list flat using a nested comprehension and print it.

Expected output:
[1, 2, 3, 4, 5, 6]

Quick Quiz

Q1.

What is [x * 2 for x in range(4)]?

Q2.

What is [n for n in range(10) if n % 3 == 0]?

Q3.

Where does if-else go in a comprehension that transforms every item?

Q4.

What does {w: len(w) for w in ["hi", "hello"]} create?

Q5.

What does (x * x for x in range(5)) create?