Skip to the page

Python core · Concept

Iterables, iterators and generators

The interviewer asks

What's the difference between an iterable, an iterator and a generator? What actually happens when a for loop runs?

Then

Follow-ups the interviewer asks next

  1. Write a class-based iterator over a date range, then the same as a generator.
  2. Why does looping over the same generator twice give nothing the second time?
  3. What does yield from add over a loop with yield?
  4. What happens if a generator reads a file and you stop halfway?

The answer

What a strong answer covers

  • An iterable has __iter__ returning an iterator; an iterator has __next__ (raising StopIteration at the end) and __iter__ returning itself.
  • for calls iter() once, then next() until StopIteration.
  • A generator is an iterator made by a function with yield; its state pauses between next() calls, so it's lazy and single-pass.
  • yield from delegates to another iterable and passes send()/throw() through. StopIteration raised inside a generator becomes RuntimeError (PEP 479).
  • Stopping early: the generator is closed when garbage-collected (or with .close()), which runs its finally/with cleanup.
  • itertools: islice, chain, groupby (needs sorted input), batched (3.12).

The red pen

Common traps

Avoid:"a generator is a function that returns a list"; not knowing generators are exhausted after one pass.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview