Generating functions: What are the advantages of using them?

Asked

Viewed 174 times

1

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)

Codes with the use of generating function and without generating function have the same output. There is some advantage in using generating function/Yield?

I still find the Yield clause confusing!

  • 2

    I think it can be related and perhaps duplicated to one of these: https://answall.com/questions/218091/generator-expressions/218150#218150, https://answall.com/questions/921/para-que-serve-o-yield/925#925, https://answall.com/questions/191752/como-works-o-Yield-no-javascript/191780#191780 ... This last link is not python but the answer explains well what are/advantages. A great advantage is not taking up space (very little) in memory, especially when it is a large data set that will only be consumed (used) once, it is unnecessary to walk with it behind

  • If my answer satisfied your question, please mark it as correct.

1 answer

2

In a very basic way, generators are lazy, that is, the next element to be "spit out" will be processed upon request, unlike a list where all elements are processed and are in memory.

Another difference is that the generator can only be run once, if you try to access it after you arrive at the end, you will receive the excision StopIteration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.