Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 811
Jason Avatar asked Oct 16 '22 13:10

Jason


2 Answers

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.

like image 143
abc Avatar answered Oct 21 '22 07:10

abc


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

like image 37
Chris Mueller Avatar answered Oct 21 '22 07:10

Chris Mueller