How does the python iter () built-in function convert a python list into an iterator?

I read my materials saying that a python iterator should have both a method __iter__and a __next__, but for an iterable it just needs to __iter__. I check the list and find that it has no method __next__. When used iter()on it, it will become an iterator. iter()Does that mean adding a method __next__to the list to convert it to an iterator? If so, how does this happen?

+4
source share
1 answer

No. iterreturns an iterator; it does not convert the list to an iterator. It does not modify the list at all, and, of course, the list does not receive the method __next__.

>>> x = [1,2]
>>> it = iter(x)
>>> it
<list_iterator object at 0x101c021d0>
>>> x.__next__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__next__'
>>>

Lists are iterators, not iterators. They implement the method __iter__, so they are iterable:

>>> x.__iter__
<method-wrapper '__iter__' of list object at 0x101bcf248>

But not __next__, therefore they are not iterators:

>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not an iterator

Iterators themselves are iterable as they implement __iter__. Consider:

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> it = iter(x)
>>> it
<list_iterator object at 0x101c02358>
>>> it.__iter__
<method-wrapper '__iter__' of list_iterator object at 0x101c02358>

Most iterators should just return when you use iterthem:

>>> it2 = iter(it)
>>> it, it2
(<list_iterator object at 0x101c02358>, <list_iterator object at 0x101c02358>)
>>> it is it2
True
>>>

In fact, this is an iterator protocol requirement :

" __iter__(), , , .

, :

>>> next(it)
1
>>> next(it2)
2
>>> next(it)
3
>>> next(it)
4
>>> next(it2)
5
>>> list(it)
[6, 7, 8, 9]
>>> next(it2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

, __iter__ __next__, , __iter__. , __iter__, , __next__.

+4

Source: https://habr.com/ru/post/1682842/


All Articles