0

What is yields for excately?

Why this: def countdown(): i=5 while i > 0: yield i i -= 1 for i in countdown(): print(i) Instead of this: def countdown(): i = 6 while i > 0: i -= 1 print(i) The first one was to explain how yield works, i just miss the point why we don't use the second solution instead of it?

26th Dec 2019, 1:11 AM
Akos Merey
Akos Merey - avatar
3 Answers
+ 2
First solution use for "lazy evaluation". It this saves memory and is often used in real projects.
26th Dec 2019, 4:27 AM
Alexey Rubtsov
Alexey Rubtsov - avatar
+ 1
Yield allows you to create a number of results pertaining to your definition. Remember, Return will only produce one result. Back to Yield - So you need a number of results, but instead of printing these results, you may wish to operate upon them later in the code, possibly only printing out those results which are still valid. Using yield instead of print gives you more control over your final output configuration.
26th Dec 2019, 5:14 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Thanks a lot guys! I need to learn a lot...
30th Dec 2019, 1:21 AM
Akos Merey
Akos Merey - avatar