How does the Python iter() function work?

2020-06-30 06:11发布

问题:

The following code confuses me:

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(*([iter(a)]*2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>> iter(a)
<listiterator object at 0x7f3e9920cf50>
>>> iter(a).next()
0
>>> iter(a).next()
0
>>> iter(a).next()
0

next() is always returning 0. So, how does the iter function work?

回答1:

You are creating a new iterator each time. Each new iterator starts at the beginning, they are all independent.

Create the iterator once, then iterate over that one instance:

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a_iter = iter(a)
>>> next(a_iter)
0
>>> next(a_iter)
1
>>> next(a_iter)
2

I used the next() function rather than calling the iterator.next() method; Python 3 renames the latter to iterator.__next__() but the next() function will call the right 'spelling', just like len() is used to call object.__len__.