So, according to the app, generators are like for loops, but they have a yield statement, instead of return. Why do we use generators then? They're practically the same. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

So, according to the app, generators are like for loops, but they have a yield statement, instead of return. Why do we use generators then? They're practically the same.

23rd Sep 2016, 12:19 PM
1-up Man
1-up Man - avatar
3 Answers
+ 1
I'm gonna assume that you mean function instead of for loops, otherwise your words don't make sense. Despite being basically functions with yield instead of return, generators are closer to lists than to functions in how you manipulate them, ie you can iterate through them with a loop. This wouldn't make sense for a function since the value returned is always the same for given parameters (save for cases where you use static variables). Instead of containing all the values like a list, a generator describes a way to generate them. You can even generate values indefinitely.
23rd Sep 2016, 1:41 PM
Zen
Zen - avatar
0
I still don't get it. Why not just use a func, which will actually do the operation, instead of a generator, which just describes how?
23rd Sep 2016, 1:54 PM
1-up Man
1-up Man - avatar
- 1
Sorry to dig this topic. But here we go... So, as @Zen said, you can generate values indefinitely. I would like to see you try to do that with a list. Also, generators lazily compute exactly what you need. For instance, if you tried to take the sum of all prime numbers below 2,000,000,000 you would have a huge memory impact with a list. Not sure it would not crash at all. With generators, you just need room to store the value of the prime and the current value of the sum. So much more efficient to do it that way. It is not even that much slower, actually
17th Feb 2017, 4:16 AM
Amaras A
Amaras A - avatar