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

PY-101 ยท Advanced Python

Iterators

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

53of 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

    An iterable is anything you can loop over, such as a list or a string. Calling iter() on it gives an iterator, an object that hands out one item each time you call next() and raises StopIteration when it runs out. Every for loop does exactly this behind the scenes.

    • Use iter() and next()
    • Know what StopIteration means
    • Write a simple iterator class

    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.

    Iterators, running
    1. it = iter(["red", "amber", "green"])
    2. print(next(it))
    3. print(next(it))
    4. print(next(it))
    5. try:
    6. next(it)
    7. except StopIteration:
    8. print("No more lights")
    9. class Countdown:
    10. def __init__(self, start):
    11. self.n = start
    12. def __iter__(self):
    13. return self
    14. def __next__(self):
    15. if self.n == 0:
    16. raise StopIteration
    17. self.n -= 1
    18. return self.n + 1
    19. print(list(Countdown(3)))
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemA for loop over a million-line file does not load the file first. It asks for one line, then the next, then the next. That "give me the next one" protocol is iteration.
    2. The Python ideait = iter(iterable)An iterable is anything you can loop over, such as a list or a string.
    3. In real lifeDatabase libraries return results as iterators, so a query over millions of rows does not need millions of rows in memory.

    Start with a question

    A for loop over a million-line file does not load the file first. It asks for one line, then the next, then the next. That "give me the next one" protocol is iteration.

    Files, database results, zip, map and generators are all iterators. Knowing the protocol explains how they behave.

    Explain it like I'm 10

    An iterator is a sweet dispenser: each press of the button gives you the next sweet, until it is empty.

    The technical explanation

    it = iter([1, 2]), then next(it) gives 1, then 2, then raises StopIteration.

    A for loop calls iter() once and next() each round, stopping quietly at StopIteration.

    A class becomes an iterator by defining __iter__ (return self) and __next__.

    Syntax

    it = iter(iterable)
    next(it)

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

    Real-world scenario

    Database libraries return results as iterators, so a query over millions of rows does not need millions of rows in memory.

    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. What does next() do?
    2. 2. What is raised when an iterator is empty?
    3. 3. Is a list an iterator?
    4. 4. Which method makes a class an iterator?
    5. 5. Loop over the same iterator twice?

    Questions people ask

    What is the difference between an iterable and an iterator?

    An iterable can produce an iterator (lists, strings, dicts). An iterator remembers its position and gives the next value with next(). Iterators are iterables too.

    Why does my zip or map result go empty after one use?

    zip and map return iterators, which are used up after one pass. Convert to a list if you need it more than once.

    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 an iterable and an iterator?

    An iterable can produce an iterator (lists, strings, dicts). An iterator remembers its position and gives the next value with next(). Iterators are iterables too.

    beginner Why does my zip or map result go empty after one use?

    zip and map return iterators, which are used up after one pass. Convert to a list if you need it more than once.

    intermediate What does next() do?

    Returns the next item. It fetches the next value.

    intermediate What is raised when an iterator is empty?

    StopIteration. StopIteration ends the iteration.

    Quick revision

    Remember

    • Use iter() and next()
    • Know what StopIteration means
    • Write a simple iterator class
    • An iterator is used up once you loop through it. Loop again and you get nothing. Make a fresh one with iter() if you need another pass.

    Syntax

    it = iter(iterable)
    next(it)

    Official documentation