I want to use next
to skip one or more items returned from a generator. Here is a simplified example designed to skip one item per loop (in actual use, I'd test n
and depending on the result, may repeat the next()
and the generator is from a package I don't control):
def gen():
for i in range(10):
yield i
for g in gen():
n = next(gen())
print(g, n)
I expected the result to be
0 1
2 3
etc.
Instead I got
0 0
1 0
etc.
What am I doing wrong?
There's nothing wrong here protocol-wise or in theory that would stop you from writing such code. An exhausted iterator it will throw StopIteration on every subsequent call to it. __next__ , so the for loop technically won't mind if you exhaust the iterator with a next / __next__ call in the loop body.
You can use the continue statement if you need to skip the current iteration of a for or while loop and move onto the next iteration.
The python next function is responsible for returning the next item in the iterator. The function takes two arguments as the input, i.e, the iterator and a default value. Then the function returns the element. The python next method calls on iterators and throws an error if no item is present.
next statement is an iterative, incremental loop statement used to repeat a sequence of statements for a specific number of occurrences. A for... next loop executes a set of statements for successive values of a variable until a limiting value is encountered.
You're making a new generator each time you call gen()
. Each new generator starts from 0.
Instead, you can call it once and capture the return value.
def gen():
for i in range(10):
yield i
x = gen()
for g in x:
n = next(x)
print(g, n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With