[Tutor] Iterator vs. iterable cheatsheet, was Re: iter class

Peter Otten __peter__ at web.de
Fri Jan 24 10:22:15 CET 2014


+----------+--------------------+------------------------+
|          | __iter__           | __next__               |
+----------+--------------------+------------------------+
| iterable | return an iterator | not available          |
+----------+--------------------+------------------------+
| iterator | return self        | return next item       |
|          |                    | or raise StopIteration |
+----------+--------------------+------------------------+

iter(x) is x --> True:      x is an iterator
                 False:     x is an iterable
                 raises Exception: x is neither iterator nor iterable

Once next(it) raises a StopIteration on a well-behaved iterator it must 
continue to raise `StopIteration`s on subsequent next(it) calls.

There's an odd outlier that I probably shouldn't tell you about: 
classes with a __getitem__() method behave like iterators. An eventual 
IndexError exception is propagated as StopIteration:

>>> class A:
...     def __getitem__(self, index):
...             if index > 2:
...                     raise IndexError
...             return index * index
... 
>>> for item in A():
...     print(item)
... 
0
1
4




More information about the Tutor mailing list