+ 3

Why do we need generator in python

4th Aug 2019, 6:34 PM
SUNDARAMAN IYER
SUNDARAMAN IYER - avatar
3 Answers
+ 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
4th Aug 2019, 7:04 PM
Tibor Santa
Tibor Santa - avatar
+ 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.
7th Aug 2019, 10:21 AM
Mateusz R
Mateusz R - avatar