If I execute,
a = iter([1,2,3])
for x in a:
print(x)
if x==1:
z=next(a)
I get
1
3
which I expect, since the call to next
advances the iterator and skips the 2
.
However in interactive mode (command line), if I remove the z=
assignment, and only call next
, it behaves very differently.
>>> a = iter([1,2,3])
>>> for x in a:
... print(x)
... if x==1:
... next(a)
gives me
1
2
3
I'm using Python 3.8.8 in Windows 64 bits. Is this expected? It only happens in interactive mode.
Interpreter echoing back the return value of next()
in addition to x
being printed each iteration.
>>> a = iter([1,2,3])
>>> for x in a:
... print(x)
... if x==1:
... next(a)
So 1 and 3 is the output of print(x)
, 2 the return value from next()
. If you assign the output of z=next()
things work as expected 1,3
because your z isn't returning or printing. Assigning the result of "next(a)" to a variable inhibits the printing of its' result so that just the alternate values that the "x" loop variable are printed