Distinguish Iterables and Iterators
Core idea
An iterable supplies an iterator through iter(source). An iterator tracks traversal progress and supplies the next item through next(it). A list can create fresh independent iterators; an iterator returns itself from iter(it). A for loop obtains an iterator and consumes it until exhaustion. No numeric indexing is required.
items = [3, 7]a = iter(items)b = iter(items)print(next(a), next(a), next(b))Each list iterator has its own position.
An iterator returns itself
it = iter([4, 8])print(iter(it) is it)print(list(it))print(list(it))Converting the iterator to a list consumes the remaining items.
Iterable without indexing
class Labels: def __iter__(self): return iter(("red", "blue"))for label in Labels(): print(label)The class provides an iterator instead of implementing indexing.
Common mistake
Not every iterable is reusable. Generators and other iterators are generally single-pass; calling iter again does not rewind them.
Practice
Create a class whose iter returns a fresh iterator over three labels. Run two loops and compare with consuming one iterator twice.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Iterables and iterators
Check your understanding of iterable and iterator.
What is printed?
items = [2, 5]a = iter(items)b = iter(items)print(next(a), next(b))What is printed?
it = iter((1, 2))print(iter(it) is it)What is printed?
it = iter([6])print(list(it), list(it))Which statement describes an iterable?