Search code examples
python-3.xfiltergenerator

What are the upsides of generators in python 3?


I know that you can use generators/list comprehensions as filters. You can do a lot with lists but what can you do with generators? Python would only make such thing as a generator if it is useful.


Solution

  • The biggest benefit of a generator is that it doesn't need to reserve memory for every element of a sequence, it generates each item as needed.

    Because of this, a generator doesn't need to have a defined size. It can generate an infinite sequence if needed.