Skip to the solution
MediumDSA6 min read

What is the difference between an iterable and an iterator?

1.1k views

The problem

Question presented to candidate: "People use 'iterable' and 'iterator' as if they meant the same thing. What exactly is the difference in Python? If I give you a list and a generator, which is which, and why can I loop over the list twice but not the generator?"

What a strong answer should cover:

  • An iterable is anything iter() can turn into an iterator: it defines __iter__ (or the older __getitem__ sequence protocol). An iterator is the object that actually produces values: it defines __next__, plus an __iter__ that returns itself
  • next() on an exhausted iterator raises StopIteration; iterators are single-pass and never rewind
  • A container such as a list hands out a new, independent iterator on every iter() call, so it can be looped over many times; a generator, map, zip, enumerate or a file object is its own iterator, so it is consumed once
  • Every iterator is iterable, but not every iterable is an iterator (isinstance(x, Iterator) vs Iterable, and why iter(x) is x is the quick test)
  • Practical consequences: in, any(), sum() partially or fully consume an iterator; the right design is an iterable class whose __iter__ returns a fresh iterator (often a generator)
  • The reliable "is it iterable?" check is calling iter() and catching TypeError, because collections.abc.Iterable misses __getitem__-only classes

Code / implementation expected: Optional β€” a small class pair (container plus iterator) or a demonstration that list(gen) is empty the second time.

  • iterators

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonA list, its iterator, and writing both roles yourself
Python__getitem__ fallback, iter(callable, sentinel), and single-pass traps

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 39 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What are dunder (magic) methods?

Continue