+ 2
Can someone explain how this generator works? I can't get my head around it.
6 Respostas
+ 6
A normal function stops its execution with the return statement.
A generator function only suspends with the yield statement. When you ask the next value from the generator, the execution continues from that yield point.
You get the next value by iterating through the generator in a for loop, or one by one using the next() function.
More in-depth article:
https://realpython.com/introduction-to-JUMP_LINK__&&__python__&&__JUMP_LINK-generators/
In your program you use the generator twice in different ways. When you use it as an iterable in for loop, you just retrieve each value (but don't use the i variable). The generator itself prints the count values.
Inside each iteration of the for loop you call the generator once again (but this is a separate and different loop) and materialize all the values in a list. Still the generator itself prints each value as they are added to the list.
+ 3
Angie AdeT What is the expected output?
If it's supposed to gradually count down as implied by the function name, you would need to change your for loop from:
----
for i in countdown(5):
print(list(countdown (5)))
----
to
----
for i in countdown(5):
print(list(countdown (i)))
----
+ 2
there are 3 processes :
1. List
2a. yield in generator
2b. yield for building list
1. begin 5 remember 5
2a. all yields of the generator from the beginning
2b. list itself
Building list means output of next until stop.
but the 2a belongs to it, because it is in the generator memory.
+ 2
David, why should we call the function countdown again in second line:
for i in countdown(5):
print(list(countdown (i))) # ???
Why shouldn't it be like this:
def countdown(i):
while i > 0:
yield i
i -= 1
for i in countdown(5):
print(i,end=', ')
# result: 5, 4, 3, 2, 1,
+ 2
Thanks for the answers! The program itself doesn't have an objective I was just playing with it to understand generators and couldn't figure this one out.
I understand the sequence is as follows:
- The for calls generator(5) which then works through the loop printing 5-1.
- List builds the list and then it's printed.
Is this right?
But then I don't get what happens with the for. If it's going through 5-1 from generator shouldn't 5 be already done with the first print, and it go 4-5-4-etc? And it going 5-5-4-3-... And 4-5-4-3-... is it because they share "i"?
Thanks!
+ 2
yes it is.
under the hood the generator function is a closure.