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.