Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Python generator skips steps with for loop

Trying to understand generators, I write:

def counter():
    n = 1
    while n <= 10:
        yield n
        n += 1

If I then manually enter

c = counter()

... followed repeatedly by

print c.next()

I get 1,2,3, etc. But if I run

for i in c:
    print c.next()

I get 2,4,6,8... I've stared at this for too long. What am I missing, please?

like image 545
Patrick Dennis Avatar asked Dec 22 '25 04:12

Patrick Dennis


2 Answers

.next() iterates on the generator you have just created, just the same way when you are doing

for i in c 

That's why you only have pair numbers in your second approach

Just type:

for i in c:
    print i
like image 135
mvelay Avatar answered Dec 23 '25 22:12

mvelay


for i in c:
    print c.next()

is essentially the same as

c_iter = iter(c)
while True:
    try:
        i = c_iter.next()
    except StopIteration:
        break
    print c_iter.next()

Your for loop is getting a value from the generator, then ignoring it and fetching another one to print.

like image 25
chepner Avatar answered Dec 23 '25 21:12

chepner