foosion
foosion

Reputation: 7898

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?

Upvotes: 9

Views: 1871

Answers (1)

khelwood
khelwood

Reputation: 59113

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)

Upvotes: 9

Related Questions