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?
.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
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.
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