Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: next in for loop

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?

like image 891
foosion Avatar asked Apr 06 '19 22:04

foosion


People also ask

Can you use next in a loop Python?

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.

How do you go next to a for loop in Python?

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.

How does next () work in Python?

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.

What does next do in a for loop?

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.


1 Answers

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)
like image 134
khelwood Avatar answered Oct 12 '22 22:10

khelwood