Python Generator: Confusing Result

I play with generators to better understand how they work, but I'm confused by the result of the following code snippet:

>>> def gen(): ... for i in range(5): ... yield i ... >>> count=gen() >>> for i in count: ... print count.next() ... 1 3 Traceback (most recent call last): File "<stdin>", line 2, in <module> StopIteration >>> 

What's going on here? It looks like since it falls into the string "for i in count:", the generator gives the first value. I'm not sure.

EDIT: I have to add that I'm not trying to β€œget it right”. I'm trying to break things down to see how Python reacts. I learn more about the language when I make mistakes. This mistake made me stump, but now everything is clear. So far, all the answers have been short and sweet. Thank you all!

+5
source share
3 answers

Your code should look like this

Code:

 def gen(): for i in range(5): yield i count=gen() for i in count: print i 

output:

 0 1 2 3 4 

Notes:

When you loop for i in count , you are trying to get the next element again here count.next() , you are trying to get the second element. So you are trying to get the +2 element from the current position

So what happens in your code is the following:

:

1. for i in count here we get the following value, which is 0

2. print count.next() is called again and the next value is printed, so 1 is printed

3. for i in count here the next value is called again, which is 2

4. print count.next() is called again here and the next value is printed, so 3 is printed

5. for i in count , the following value is again called here: 4

6. Finally, you call print count.next() since there is no value in the generator. You specified a StopIteration exception

+5
source

Since the "for" loop is already sorting through your generator values, at each step two values ​​are given: one in the "for" and one in the body of the loop.

+3
source

for i in count: already calls the next one (and assigns the value i ). Then your code calls the following code again.

If you just want to print each value

 for i in count: print i 

or a long way

 while True: try: print count.next() except StopIteration, si: break 
+2
source

Source: https://habr.com/ru/post/1233600/


All Articles