⚡0 XP🔥0

Iterators and Generators

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

How for loops really work - iterables, iterators, iter() and next(), building iterator classes, and writing memory-efficient generators with yield.

Iterables and iterators#

  • An iterable is anything you can loop over: lists, strings, tuples, dicts, sets, files, ranges.
  • An iterator is the object that actually produces the values one at a time and remembers where it is.

You get an iterator from an iterable with iter(), and ask for values with next():

▶ Try it YourselfPython
Ctrl + Enter to run

How a for loop really works#

This for loop:

for f in fruits:
    print(f)

is what Python does behind the scenes:

it = iter(fruits)
while True:
    try:
        f = next(it)
    except StopIteration:
        break
    print(f)
हिंदी में समझें

Iterable = ऐसी चीज़ जिस पर loop चलाया जा सके (list, string, file...)। Iterator = एक "pointer" जो याद रखता है कि अभी कहाँ तक पहुँचे हैं, और हर बार next() बोलने पर अगली value देता है।

इसे किताब और bookmark की तरह समझें - किताब (iterable) में सारे पन्ने हैं, bookmark (iterator) याद रखता है कि आप किस पन्ने पर हैं। जब पन्ने खत्म हो जाते हैं, तो StopIteration आता है और for loop अपने आप रुक जाता है।

Creating your own iterator class#

Implement two dunder methods:

  • __iter__() → returns the iterator object (usually self)
  • __next__() → returns the next value, or raises StopIteration
▶ Try it YourselfPython
Ctrl + Enter to run

That's a lot of code for a simple idea. Generators make it much easier.

Generators and yield#

A generator function looks like a normal function but uses yield instead of return. Calling it doesn't run the code immediately - it returns a generator object that produces values on demand.

▶ Try it YourselfPython
Ctrl + Enter to run

return vs yield#

return yield
sends one value and ends the function sends a value and pauses the function
local variables are lost local variables are remembered
function runs once function resumes on each next()
हिंदी में समझें

return = काम खत्म करके जवाब दे दो, function बंद। yield = एक जवाब दो, लेकिन रुककर इंतज़ार करो - अगली बार माँगने पर ठीक वहीं से आगे शुरू करो जहाँ रुके थे।

जैसे चाय वाला: return = एक बार में पूरा 100 कप चाय का बर्तन दे देना (भारी, जगह चाहिए)। yield = ग्राहक जब माँगे, तब एक कप बनाकर देना - कम जगह, कम बर्बादी। इसीलिए generators बड़ी files और बड़े data के लिए बहुत उपयोगी हैं।

Why generators? Memory efficiency#

A list stores all values in memory. A generator stores only the current state:

▶ Try it YourselfPython
Ctrl + Enter to run

Real-world use: processing a large file line by line#

def read_large_log(path):
    with open(path) as f:
        for line in f:
            if "ERROR" in line:
                yield line.strip()

for error in read_large_log("server.log"):    # works even for a 10 GB file
    print(error)

Infinite generators#

Generators can run forever - you take only what you need:

▶ Try it YourselfPython
Ctrl + Enter to run

Generator pipelines#

Chain generators so each step processes one item at a time:

▶ Try it YourselfPython
Ctrl + Enter to run

Useful tools: itertools#

▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

A generator can be consumed only once:

g = (x for x in range(3))
print(list(g))   # [0, 1, 2]
print(list(g))   # []  - already exhausted

Summary#

  • Iterables can be looped over; iterators produce values with next() and raise StopIteration at the end.
  • A for loop calls iter() once and next() repeatedly.
  • Iterator classes implement __iter__ and __next__.
  • Generator functions use yield; they pause and resume, keeping their state.
  • Generators are memory-efficient (one value at a time) and can be infinite; they can be consumed only once.

Practice Exercises

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

1

Even number generator

Write a generator function evens(limit) that yields the even numbers from 0 up to and including limit.

2

Fibonacci generator

Write a generator fibonacci(n) that yields the first n Fibonacci numbers starting 0, 1, 1, 2, 3...

3

Countdown iterator class

Create a class Countdown(start) that can be used in a for loop and yields start, start-1, ..., 1. Implement __iter__ and __next__.

Quick Quiz

Q1.

What does next() do on an iterator?

Q2.

What makes a function a generator?

Q3.

What happens after a generator has given all its values and you loop over it again?

Q4.

Why are generators memory-efficient?

Q5.

What is the difference between return and yield?