Welcome to the Treehouse Community
Looking to learn something new?
Why not use generators all the time?
If generators are more memory / system efficient, why not use them all the time in place of for loops?
Chris FreemanTreehouse Moderator 67,989 Points
A bit of clarification: a generator would not replace a for loop specifically. A generator may be used as the iterable object target of the
for loop. The function
range() is a common generator used in
for loops. Also, inside many generators,
for loops are used to cycle through the data being generated.
Using generators in areas that don't involve much data might make the code less obvious or less readable when compared to simply instantiating the data in a straightforward fashion.
In the end, it comes down to speed of code implementation vs speed of execution. If the difference in execution would be negligible, the speed of coding is more important. Sometimes being too cleaver is a pitfall to those that follow in support the code.
Generators can be a boon in cases where all the data might not be consumed in a loop due such as search for the first instance of something in a huge list. Once found, generating the remaining data can be abandoned with having wasted time and memory that generating all the data before the search would cause.
Not sure if I answered your question. Post back if you have more questions!!