Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.1 — How for Really Works: Iterables and Iterators
Python · Example 1 of 2

iter and next by hand

Add a fourth number to the list and one more next(it) call. Predict what happens before you run.

A for loop asks an object for an iterator with iter(), then calls next() on it again and again until it raises StopIteration. Knowing the difference between an iterable (can be looped over) and an iterator (remembers its place, used up once) explains many surprises.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Use iter and next by hand to print the three letters of "abc", one per line, and then show what next(it, "done") returns afterwards.

02

Write an iterator class Evens that takes a limit and produces the even numbers from 0 up to but not including limit. Print list(Evens(7)).

03

Write an iterable class Words that takes a sentence and loops over its words. Show that you can loop over the same object twice.

Explain it without notes

01

Explain what a for loop does, step by step, in terms of iter and next.

02

What is the difference between an iterable and an iterator? Give an example of each and say which one can be looped over twice.

03

How do you write an iterator class, and what makes it different from an iterable class?

04

Why does looping over the same iterator a second time produce nothing, and how do you avoid the bug?

05

What goes wrong if you add or remove items from a list while looping over it, and what happens with a dictionary?

iter and next by hand
Sign in to run this example in your browser.

Expected output

list type: list
iterator type: list_iterator
10
20
30
StopIteration: the iterator is used up
iter(it) is it: True
iter(numbers) is numbers: False
two iterators are separate: True