Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Advanced Objects Emulating Built-ins

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?

1 Answer

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 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!!