Iterables and Iterators · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. Which methods must an object implement to be an iterator?
2. What does this print?
numbers = [1, 2, 3]
it = iter(numbers)
print(list(it), list(it))
3. What does this print?
d = {'a': 1, 'b': 2}
keys = d.keys()
print(list(keys), list(keys))
4. What does this print?
class Countdown:
    def __init__(self, start):
        self.n = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

c = Countdown(3)
print(list(c), sum(c))
5. What does this print?
it = iter('abcde')
next(it)
next(it)
print(''.join(it))
6. Which of these is an iterator (and therefore single-use)?
7. What does this print?
class Squares:
    def __getitem__(self, i):
        if i >= 4:
            raise IndexError
        return i * i

print(list(Squares()))
8. What does this print?
def counter():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc

print(list(iter(counter(), 4)))
9. A class implements __iter__ and __len__ but not __getitem__ or __reversed__. What does reversed(obj) do?
10. What does this print?
nums = map(int, '3 1 2'.split())
total = sum(nums)
count = len(list(nums))
print(total, count)
11. A function needs to loop over its data argument twice. Which check detects that it was given an iterator?
12. What does this print?
import itertools
print(list(zip('xyz', itertools.cycle([0, 1]))))

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: A re-iterable countdown

The Countdown class below is its own iterator, so it can only be looped over once.

Refactor it into a proper iterable: Countdown(start) should produce start, start - 1, …, 1 every time it is iterated. Put the iteration logic in a separate iterator class CountdownIterator (it may be nested inside Countdown or defined at module level) that implements the iterator protocol, so that:

- iter(Countdown(3)) returns a new CountdownIterator, not the Countdown itself - each iterator is independent and stays exhausted once it's done - len(Countdown(3)) is 3, and Countdown(0) produces nothing

Hints (3)
  1. Keep only the data (start) in Countdown. Move current and __next__ into CountdownIterator.
  2. Countdown.__iter__ should return CountdownIterator(self.start) (or self.CountdownIterator(...) if nested).
  3. Once current reaches 0 it never increases again, so the iterator stays exhausted automatically.
Show a solution
class Countdown:
    def __init__(self, start):
        self.start = start

    def __len__(self):
        return self.start

    def __iter__(self):
        return self.CountdownIterator(self.start)

    class CountdownIterator:
        def __init__(self, start):
            self.current = start

        def __iter__(self):
            return self

        def __next__(self):
            if self.current <= 0:
                raise StopIteration
            self.current -= 1
            return self.current + 1

Exercise 2: Build your own cycle

Write an iterator class Cycle(iterable) that repeats the items of iterable forever, like itertools.cycle (don't use itertools).

It must work with any iterable, including a one-shot iterator such as iter([1, 2]) or a map object, which can only be read once. So during the first pass, remember each item as you hand it out, and replay the remembered items afterwards.

If the iterable is empty, next() should raise StopIteration straight away.

Hints (3)
  1. Call iter(iterable) once in __init__ and pull items from it with next() during the first pass.
  2. Append each item to a list as you return it. When the source raises StopIteration, switch to replaying that list with a wrapping index (%).
  3. If the saved list is still empty after the source is exhausted, raise StopIteration.
Show a solution
class Cycle:
    def __init__(self, iterable):
        self._source = iter(iterable)
        self._saved = []
        self._first_pass = True
        self._i = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._first_pass:
            try:
                item = next(self._source)
            except StopIteration:
                self._first_pass = False
            else:
                self._saved.append(item)
                return item
        if not self._saved:
            raise StopIteration
        item = self._saved[self._i % len(self._saved)]
        self._i += 1
        return item

Exercise 3: Header rows with next()

Write parse_records(lines). lines is any iterable of strings (a list, a file, a generator…) laid out like this:

text name,age,score <- column names str,int,float <- column types Alice,30,88.5 <- data rows Bob,25,92.0

Return a list of dictionaries, one per data row, with each value converted to its column's type: [{'name': 'Alice', 'age': 30, 'score': 88.5}, …]. Lines may end with '\n'. If there are no lines at all, return [].

Use an iterator: take the two header lines with next() and loop over the rest, so the function also works when lines is a one-shot iterator.

Hints (3)
  1. Start with it = iter(lines). Then next(it) gives the first line, the second next(it) the second, and for line in it continues from line 3.
  2. next(it, None) returns None instead of raising when there are no lines.
  3. Map type names to functions with a dict such as {'str': str, 'int': int, 'float': float}, then zip names, casts and values together.
Show a solution
CASTS = {'str': str, 'int': int, 'float': float}

def parse_records(lines):
    it = iter(lines)
    header = next(it, None)
    if header is None:
        return []
    headers = header.strip().split(',')
    casts = [CASTS[t] for t in next(it).strip().split(',')]
    return [
        {name: cast(value)
         for name, cast, value in zip(headers, casts, line.strip().split(','))}
        for line in it
    ]

Exercise 4: Two passes, one iterator

Write percent_of_max(values) that returns a list with each value expressed as a percentage of the largest value, rounded to 1 decimal place: percent_of_max([50, 100, 25]) → [50.0, 100.0, 25.0].

The function needs two passes over the data (one to find the maximum, one to compute the percentages). Make it work correctly for any iterable, including iterators like map(...) objects and generators, without needlessly copying data that is already a re-iterable collection. An empty input returns [].

Hints (3)
  1. With an iterator, max() uses up every value, so the comprehension afterwards sees nothing.
  2. iter(values) is values is True only for iterators. In that case, convert to a list first.
  3. max(values, default=None) avoids an error on empty input.
Show a solution
def percent_of_max(values):
    if iter(values) is values:     # an iterator: materialize it once
        values = list(values)
    biggest = max(values, default=None)
    if biggest is None:
        return []
    return [round(v / biggest * 100, 1) for v in values]