Advertisement
Beginner Python, Iterators & the Iterator Protocol

What is the difference between an iterable and an iterator in Python?

Short answer

An iterable is any object implementing __iter__() that returns an iterator, such as lists, tuples, and dicts -- you can loop over it repeatedly.

Save Python mock interview
Advertisement
AModel answer
An iterable is any object implementing __iter__() that returns an iterator, such as lists, tuples, and dicts -- you can loop over it repeatedly. An iterator is an object implementing both __iter__() (returning itself) and __next__() (returning the next value or raising StopIteration) -- it's stateful and exhausted after one full pass.
nums = [1, 2, 3]         # iterable
it = iter(nums)          # iterator
print(next(it))          # 1
print(next(it))          # 2
Real-world example
A file object is an iterator over its lines -- you can only read through it once before needing to reopen or seek back to the start.
Likely follow-ups
  • Can an object be both an iterable and an iterator?
  • What happens if you call next() on an exhausted iterator?
Related topics