Here's the explanation I use in teaching Python classes:
An ITERABLE is:
for x in iterable: ...
oriter()
that will return an ITERATOR: iter(obj)
or__iter__
that returns a fresh ITERATOR,
or it may have a __getitem__
method suitable for indexed lookup.An ITERATOR is an object:
__next__
method that:
StopIteration
__iter__
method that returns self
).Notes:
__next__
method in Python 3 is spelt next
in Python 2, andnext()
calls that method on the object passed to it.For example:
>>> s = 'cat' # s is an ITERABLE
# s is a str object that is immutable
# s has no state
# s has a __getitem__() method
>>> t = iter(s) # t is an ITERATOR
# t has state (it starts by pointing at the "c"
# t has a next() method and an __iter__() method
>>> next(t) # the next() function returns the next value and advances the state
'c'
>>> next(t) # the next() function returns the next value and advances
'a'
>>> next(t) # the next() function returns the next value and advances
't'
>>> next(t) # next() raises StopIteration to signal that iteration is complete
Traceback (most recent call last):
...
StopIteration
>>> iter(t) is t # the iterator is self-iterable