GoingMyWay
GoingMyWay

Reputation: 17478

Why does repeatedly calling "iter(a).next()" on a list "a" never return more than the first list item?

The following code confuses me:

>>> a
[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?

Upvotes: 0

Views: 3708

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125068

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__.

Upvotes: 8

Related Questions