Lesson 29 of 60
โฎPrev Nextโฏ

PY-101 ยท Collections

Comprehensions

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

29of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก The 30-second answer

    A comprehension builds a new list, dict or set from another collection in one line: [x * 2 for x in nums]. Add if at the end to keep only some items: [x for x in nums if x > 0]. It replaces the common pattern of an empty list, a loop and append.

    • Write a list comprehension
    • Filter with if
    • Build dicts and sets the same way

    Try it

    Watch it come alive, run it yourself, then prove it. Real Python, right on this page.

    Watch Python run the example. Every variable is a jar; watch the values change and the output appear.

    Comprehensions, running
    1. prices = [100, 250, 40]
    2. with_tax = [round(p * 1.18) for p in prices]
    3. print(with_tax)
    4. cheap = [p for p in prices if p < 200]
    5. print(cheap)
    6. squares = {n: n * n for n in range(1, 4)}
    7. print(squares)
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemYou have 500 prices and need them all with 18% tax added. The loop takes four lines; a comprehension says it in one, and reads like the sentence you just said.
    2. The Python idea[expr for x in items if condition]A comprehension builds a new list, dict or set from another collection in one line: [x * 2 for x in nums].
    3. In real lifeData pipelines clean thousands of rows with lines like emails = [e.strip().lower() for e in raw if "@" in e].

    Start with a question

    You have 500 prices and need them all with 18% tax added. The loop takes four lines; a comprehension says it in one, and reads like the sentence you just said.

    Data cleaning and transformation are everywhere, and comprehensions are the idiomatic Python way to do them.

    Explain it like I'm 10

    It is like telling a helper: "for every apple in this basket, give me a sliced apple, but only the red ones". One instruction, a whole new basket.

    The technical explanation

    [expression for item in iterable] runs expression for each item and collects the results.

    [x for x in nums if x % 2 == 0] keeps only the items where the condition is True.

    {k: v for k, v in pairs} builds a dict; {x for x in items} builds a set.

    Syntax

    [expr for x in items if condition]
    {key: value for x in items}

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    Data pipelines clean thousands of rows with lines like emails = [e.strip().lower() for e in raw if "@" in e].

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. [n * 10 for n in [1, 2]]?
    2. 2. [n for n in range(6) if n % 2 == 0]?
    3. 3. Which builds a dict?
    4. 4. What does a comprehension replace?
    5. 5. When should you prefer a normal loop?

    Questions people ask

    Are list comprehensions faster than for loops?

    Usually a little, because the appending happens inside Python itself. Choose them mainly because they are shorter and clearer for simple transformations.

    What is a generator expression?

    The same syntax with round brackets, (x * 2 for x in nums). It produces values one at a time instead of building the whole list, which saves memory.

    Interview questions

    How this topic comes up in Python interviews. Answer out loud first, then open the model answer.

    beginner Are list comprehensions faster than for loops?

    Usually a little, because the appending happens inside Python itself. Choose them mainly because they are shorter and clearer for simple transformations.

    beginner What is a generator expression?

    The same syntax with round brackets, (x * 2 for x in nums). It produces values one at a time instead of building the whole list, which saves memory.

    intermediate [n * 10 for n in [1, 2]]?

    [10, 20]. Each item times 10.

    intermediate [n for n in range(6) if n % 2 == 0]?

    [0, 2, 4]. Even numbers from 0 to 5.

    Quick revision

    Remember

    • Write a list comprehension
    • Filter with if
    • Build dicts and sets the same way
    • If a comprehension needs more than one if or a nested loop to read, switch back to a normal loop. Clear beats clever.

    Syntax

    [expr for x in items if condition]
    {key: value for x in items}

    Official documentation