Save Memory with Python Generators
If you use large static iterables in Python, a list may not be an optimal choice, especially in memory-constrained applications.
A list stores the entire collection in memory. However, a generator computes and loads a single element at a time ONLY when it is required. This saves both memory and object creation time.
Of course, there are some limitations of generators too. For instance, you cannot use common list operations such as append(), slicing, etc.
Moreover, every time you want to reuse an element, it must be regenerated (see Generator.py: line 12).
Read more on StackOverflow: https://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehensions.
Thanks for reading Daily Dose of Data Science! Subscribe for free to learn something new and insightful about Python and Data Science every day. Also, get a Free Data Science PDF (250+ pages) with 200+ tips.