Generating functions: What are the advantages of using them?

2

Generating function:

def geraQuadrados(n):
        for i in range(n):
            yield i**2



    for i in geraQuadrados(5):
        print(i)

No generating function:

def novosQuadrados(n):
    l = []
    for i in range(n):
        l.append(i**2)
    return l

for i in novosQuadrados(5):
    print(i)

The codes with the use of generating function and without the generating function have the same output. Is there any advantage in using generator / yield function?

I still find the yield clause confusing!

    
asked by anonymous 05.04.2018 / 14:17

1 answer

2

In a very basic way, generators are lazy, that is, the next element to be "spat" will be processed on request, other than a list where all elements are processed and stored in memory.

Another difference is that the generator can only be traversed once, if it tries to access it after reaching the end, it will receive the StopIteration .

    
09.04.2018 / 16:13