Iterators of iterators

Steve Keller keller at no.invalid
Fri Nov 16 09:54:36 EST 2018


I wonder why iterators do have an __iter__() method?  I thought
iterable objects would have an __iter__() method (but no __next__())
to create an iterator for it, and that would have the __next__()
method but no __iter__().

    $ python3
    Python 3.5.2 (default, Nov 12 2018, 13:43:14)
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> l = [1,2,3]
    >>> next(l)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'list' object is not an iterator

This is expected, of course.

    >>> iter(l)
    <list_iterator object at 0x7f2e271d1fd0>
    >>> iter(iter(l))
    <list_iterator object at 0x7f2e278f5978>
    >>> iter(iter(iter(l)))
    <list_iterator object at 0x7f2e271d1fd0>
    >>> i = iter(iter(iter(l)))
    >>> list(i)
    [1, 2, 3]

Is there any reason or usage for this?

Steve



More information about the Python-list mailing list