MCS-201 · Unit 15

Python Advanced Concepts

Section 2 of 5

Block 4 · Unit 15Python Advanced Concepts9 min · Section 2 of 5

15.2Iterables and Iterators

Covers IGNOU MCS-201 §15.3

Every for loop in Python uses iterators behind the scenes. Understanding them explains why you can loop over lists, strings, files, dictionaries and range in the same way, and why some objects can be looped over only once.

IterableIterator
MeaningAn object you can loop overAn object that produces the values of a loop, one at a time
Has__iter__(), which returns an iterator__next__(), which returns the next value, and __iter__(), which returns itself
Exampleslist, tuple, str, dict, set, range, filesThe result of iter(list), map(...), filter(...), zip(...), files, generators
Can be looped over againYes (each loop gets a fresh iterator)No: once used up, it stays empty

iter(x) calls x.__iter__() and next(it) calls it.__next__().

What a for loop really does

for item in numbers: print(item) is equivalent to
it = iter(numbers)            # get an iterator from the iterable
while True:
    try:
        item = next(it)       # ask for the next value
    except StopIteration:     # no more values
        break
    print(item)

Writing your own iterator

A class becomes an iterator by defining __iter__ (returning self) and __next__ (returning the next value or raising StopIteration).

Key takeaways

  • Iterable: has __iter__; can be looped over many times.
  • Iterator: has __next__ and __iter__ (returning itself); used up after one pass.
  • for loops call iter() once, then next() until StopIteration.
  • map, filter, zip, files and generators are iterators.

Practice questions

Answer on paper first, then check. The explanation matters more than the letter you chose.

Question 1 · multiple choice

Which of these is an iterable but not an iterator?

Show answer

Answer: B. [1, 2, 3]

A list can produce iterators but has no __next__ itself; the other three are iterators.

Question 2 · multiple choice

What does next() raise when an iterator has no more items?

Show answer

Answer: C. StopIteration

StopIteration is how an iterator signals the end; for loops catch it automatically.

Question 3 · multiple choice

What does this program print?

Python · quiz_iter.py
it = iter("MCA")
next(it)
print(next(it), list(it), list(it))
Show answer

Answer: C. C [‘A’] []

The first next takes “M”, the second “C”; list(it) takes the remaining “A”; the iterator is then empty.

Question 4 · multiple choice

Which pair of methods must an iterator class define?

Show answer

Answer: D. __iter__ and __next__

These two make up the iterator protocol.

Question 5 · multiple choice

What is iter(x) is x for an iterator x?

Show answer

Answer: A. True

An iterator’s __iter__ returns the iterator itself, which is why for loops work on iterators directly.

Question 6 · short answer

Explain step by step how for x in [10, 20]: print(x) is executed in terms of iterators.

Show worked answer

First Python calls iter([10, 20]), which returns a list iterator. It then calls next() on that iterator, which returns 10; this is assigned to x and the body prints 10. It calls next() again, which returns 20, and prints it. The third next() call raises StopIteration; the for loop catches this exception silently and ends.

↑ ↓ move↵ openTab switch type