Python Jumpstart by Building 10 Apps Transcripts
Chapter: App 9: Real Estate Analysis App
Lecture: Concept: generator expressions

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's quickly talk about this cool concept of generator expressions. Generator expressions are sort of the next evolution from list comprehensions,
0:10 and list comprehensions of course take the idea of writing procedural code, declaring a list,
0:16 and writing some kind of loop within that loop doing a filter maybe somehow transforming the data and putting into the list.
0:24 Generator expressions do the exact same thing but instead of computing the entire thing into a list in memory
0:32 it works just like the coroutines that you get when you use the yield keyword, you don't actually do the computation,
0:38 you don't pull the item back from the get active customers in this example, you don't do the test until you start to pull items out of it,
0:45 so if you say for n in paying usernames, and you only pull three of those out, maybe within the first five of a million active customers
0:55 there are three ones who are active today well you are only going to process five customers instead of a million.
1:01 That can have a lot of really powerful positive effects for your application performance.
1:07 Now to be fair, there are certain situations where this doesn't work as well, you can't index into generators for example,
1:15 or you can for a list comprehension, every time you loop over paying usernames, you recompute this information,
1:22 so if you are going to use the item over and over and over, maybe it makes sense to use a list comprehension,
1:26 often though with these little expressions you create them, you blast over them and you are done, in that case,
1:32 generator expressions probably are the way to go.


Talk Python's Mastodon Michael Kennedy's Mastodon