Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Understanding Generators

In this lesson, you’ll learn how to create generator functions, and how to use the yield statement. Generator functions are a special kind of function that return a lazy iterator. These are objects that you can loop over like a list. However, unlike lists, lazy iterators do not store their contents in memory.

You’ll also compare list comprehensions and generator expressions. Once you’ve learned the difference in syntax, you’ll compare the memory footprint of both, and profile their performance using cProfile.

Comments & Discussion

MrSteve3000 on June 26, 2020

In your cProfile examples, I see you are using i * 2 instead of exponentiation. I tried the code both ways, and of course the generator expression is still a bit slower, but not as dramatically.

Become a Member to join the conversation.