What is the difference between an iterable and an iterator in Python?
An iterable can produce an iterator when you call iter() on it, such as a list or string. An iterator is the object that actually hands out items one at a time through next() and remembers its position. Iterators are single-use.
Explain it simply
A railway timetable (iterable) lists all the trains, and you can open it as many times as you like. A conductor walking down the coach with one finger on the current seat (iterator) can only move forward, and once he reaches the end, he is done.
Technically, an iterable has __iter__ and an iterator has both __iter__ and __next__.
Example
nums = [10, 20, 30]
it = iter(nums)
print(next(it)) # Output: 10
print(next(it)) # Output: 20
print(next(it)) # Output: 30
try:
next(it)
except StopIteration:
print("finished") # Output: finished
print(list(it)) # Output: []
print(list(nums)) # Output: [10, 20, 30]The list can be iterated again and again, but the used-up iterator returns nothing more.
What to say in the interview
"An iterable implements __iter__ and returns a fresh iterator each time. An iterator implements __next__, keeps state, raises StopIteration when finished, and can be consumed only once. Lists, tuples, strings, dicts and files are iterables; generators and file objects are iterators."
Common mistakes
- Looping twice over an iterator or generator and getting nothing the second time.