osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Iterators of iterators


On Fri, Nov 16, 2018 at 8:01 AM Steve Keller <keller at no.invalid> wrote:
>
> 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?

Iterators are required to have an __iter__ method that just returns
self. The reason is so that iterators can be used in places where an
iterable is required; e.g. so that code that is handed an iterator can
loop over it.