+ 2
Help about the Yield in Python
I have started to study the yield in python core course. - In the tutorial, there has code: def countdown(): i=5 while i>0: yield i i -= 1 for i in countdown(): print(i) - i have tried writing another code: def countdown(): i=5 while i>0: print(i) i -= 1 countdown() That has the same result. So what is the difference? P/s: iâm beginner đ
2 Answers
+ 4
They may appear the same, but your function is NoneType, the example is a generator. I will admit, it is not the best example, using a for loop to cycle through the generator is odd, but it is how to make it work in Sololearns Playground. I believe the proper implementation would be to call next() until the generator is exhausted. Also, I think you will find that print() has its limitations. Generators are also nice because the yield procedure releases the processor so it is available for other operations, this is great for resource management. For what its worth, I use generators like this:
https://www.kaggle.com/n3v375/covid-deadliest-states-and-counties#Top-Ten-deadliest-Counties-by-State
+ 4
Here you find more informations about generators:
https://realpython.com/introduction-to-JUMP_LINK__&&__python__&&__JUMP_LINK-generators/#understanding-generators
Generators getting interesting if you want to work with many datas without the need to store them into a list.
Imagine your countdown goes from 10.000 to 0.
def countdown():
for i in range(10,000, -1, -1):
yield i
Of course you can put the values into a list but you can also use next() to get the next value only when you really need it.
gen = countdown()
a = next(gen) #10.000
#some lines of codes later
a = next(gen) #9.999
This gives you more flexibility because you can also imagine an infinity list.
def even():
i = 0
while True:
i += 2
yield i
my_even = even()
Now you have theoretically all evens and you only need to call next to get them.