0

I understand how generators and iterators work, but I don't see why generators are supposed to be so useful. I saw multiple tutorials that use a prime number finder as an example, however, I always also saw ways how to achieve the same without using a generator (without storing the numbers), for example I usually found things like this:

def gen_prim(num):
    while True:
        if is_prime(num): # just some function that returns true or false if num is a prime
            yield num
        num += 1

for i in gen_prim(1000):
    if i < 1000:
        print(i)
    else:
        break

However, instead of creating a generator in the first place, we could just instead of yielding num, do print(num) inside of gen_prim right away, as we're going to do that later anyways, and can thus remove the for loop.

So, as said, I don't understand how generators are beneficial, as to me it seems they just produce more code. I would greatly appreciate an explanation of why they are considered useful and how exactly I can use them that they are beneficial to me, because as you saw, they don't seem to help me very much.

  • In your case generators *aren't* beneficial, because you're just printing the results. But if you wanted to do something else with them? – jonrsharpe May 11 '20 at 10:54
  • in this example a generator is indeed completely useless – user2717954 May 11 '20 at 10:55
  • 1
    Generators are useful if you want to break earlier. It also uses much less memory (try getting the prime numbers from 1 to 10^12 in a list comprehension). In your particular example it might not be that beneficial, though. – Jan May 11 '20 at 10:55
  • @Jan if I would want to get these primes, I would most likely print them, right? So I would do it the way I did in my example (instead of iterating over a generator printing it in the original function right away). However, I see that you said it wouldn't be very beneficial in my example, do you maybe have an example where you would want a generator to get these primes? I would really appreciate it as it would help me understand it better (BTW I read the post of which this one is a duplicate, I am still confused though). –  May 11 '20 at 11:44

0 Answers0