Jason
Jason

Reputation: 133

Why doesn't next(iter(x)) advance to the next iterable?

I am confused why the iteration code works when I assign L to iter(x), and then next(L) to iterate through the x list. As can be seen below:

x=[1,2,3,4,5]
>>> L=iter(x)
>>> next(L)
1
>>> next(L)
2
>>> next(L)
3
>>> next(L)
4
>>> next(L)
5
>>> next(L)

But when I manually write next(iter(x)) to iterate through the x list, it does not work:

next(iter(x))
1
>>> next(iter(x))
1
>>> next(iter(x))
1

Upvotes: 9

Views: 10149

Answers (2)

abc
abc

Reputation: 11949

next(iter(x))

is equivalent to

it = iter(x)
next(it)

Thus, in the second case you are repeating each time these two instructions in which you first create an iterator from the iterable, and you apply the next() function getting each time the first element.
So you never consume it, but recreate it each time.

Upvotes: 7

Chris Mueller
Chris Mueller

Reputation: 6700

In Python, iterators are objects which get used up after they are created. In your first example you create an iterator and extract its elements until it is exhausted. In your second example you create a new iterator each time, extract its first element, and then discard it (via the garbage collector).

Upvotes: 1

Related Questions