Doing:
r = r+3
will not work as expected because r
is assigned to the value just returned by the iterator, not the iterator itself. To advance the iterator, you need to call next
on it.
You can do this by first saving the iterator in a variable and looping over that:
it = iter(range(0,10))
for r in it:
This will allow you to then call next
on it inside the loop:
it = iter(range(0,10))
for r in it:
if(r==0):
print (0)
print (1)
print (2)
for _ in range(3): # Advance the iterator by 3.
next(it)
else:
print(r)
Note however that, as @StevenRumbalski said, calling next
on an empty iterator will raise a StopIteration
exception. Sometimes this behavior is desirable, but if not, you can specify a default value to return:
next(it, None)
This will effectively make the line a no-op.