Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 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!!