+ 3
Why do we need generator in python
2 Antworten
+ 4
Generators are lazy. That means, they don't need to manifest all of their values right away, but on demand whenever needed. This is very memory-efficient and particularly useful when you need to handle huge sets of data. That is their advantage compared to list comprehensions.
Compared to regular for/while loops, their strength is that they are not forced to 'step' the next value by a fixed increment, and they are not restricted to a fixed finite number of iterations. You can build infinite generators (and use as many values as you need). Example:
https://code.sololearn.com/cYlH5XVg4s75/?ref=app
+ 1
I completely agree with Santa.
One use case for generators is asynchronous programming in twisted (python library). But I believe this was used mainly on python 2. Python3 provides its own solution of coroutines.