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

PY-101 ยท Advanced Python

Generators

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

54of 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 generator is a function that uses yield instead of return. Each time you ask for a value it runs until the next yield, hands that value out and pauses, keeping its place for next time. Generators produce huge or endless sequences without storing them all in memory.

    • Write a generator with yield
    • Use generator expressions
    • Know why they save memory

    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.

    Generators, running
    1. def countdown(n):
    2. while n > 0:
    3. yield n
    4. n -= 1
    5. yield "Lift off!"
    6. for value in countdown(3):
    7. print(value)
    8. squares = (x * x for x in range(1, 6))
    9. print(sum(squares))
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemYou need the first 10 even numbers that are also multiples of 3 from an endless stream. A list would never finish building. A generator produces them on demand and stops when you do.
    2. The Python ideadef gen():A generator is a function that uses yield instead of return.
    3. In real lifeAI chat apps stream answers word by word: the model client yields each chunk as it arrives instead of waiting for the full reply.

    Start with a question

    You need the first 10 even numbers that are also multiples of 3 from an endless stream. A list would never finish building. A generator produces them on demand and stops when you do.

    Reading big files, streaming data and AI token streams all use generators so memory stays small.

    Explain it like I'm 10

    A generator is a storyteller who tells one sentence, then waits for you to say "and then?" before telling the next.

    The technical explanation

    Calling a generator function does not run it; it returns a generator object.

    Each next() runs to the next yield. The function's local variables survive between yields.

    (x * x for x in range(10)) is a generator expression: like a list comprehension, but lazy.

    Syntax

    def gen():
        yield value
    
    (expr for x in items)

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

    Real-world scenario

    AI chat apps stream answers word by word: the model client yields each chunk as it arrives instead of waiting for the full reply.

    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. Which keyword makes a function a generator?
    2. 2. What does calling a generator function return?
    3. 3. Main benefit of generators?
    4. 4. sum(x for x in range(4))?
    5. 5. What happens at yield?

    Questions people ask

    What is the difference between yield and return?

    return ends a function and sends back one value. yield sends back a value and pauses, so the function can continue and yield more later.

    When should I use a generator instead of a list?

    When the data is large, endless, or only needed once in order. Use a list when you need indexing, length or several passes.

    Interview questions

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

    beginner What is the difference between yield and return?

    return ends a function and sends back one value. yield sends back a value and pauses, so the function can continue and yield more later.

    beginner When should I use a generator instead of a list?

    When the data is large, endless, or only needed once in order. Use a list when you need indexing, length or several passes.

    intermediate Which keyword makes a function a generator?

    yield. yield makes it a generator.

    intermediate What does calling a generator function return?

    A generator object. Nothing runs until you ask for values.

    Quick revision

    Remember

    • Write a generator with yield
    • Use generator expressions
    • Know why they save memory
    • Like iterators, a generator is used up after one pass. Call the generator function again to start over.

    Syntax

    def gen():
        yield value
    
    (expr for x in items)

    Official documentation