Python Jumpstart by Building 10 Apps Transcripts
Chapter: App 9: Real Estate Analysis App
Lecture: Concept: list comprehensions
0:00 One really powerful language construct in Python is this thing called a list comprehension
0:06 that lets us take procedural code and condense it down to declarative code. Here we have a bunch of customers,
0:13 and we'd like to know just the customers who purchased today. And we don't want all the information about the customers,
0:19 we just want a list of strings that are their names. So paying_usernames is going to be the set of users who have purchased something today.
0:29 Now, this code works fine, and this is how you do this in many languages, we create lists, we loop over all the items, within out loop we do a test,
0:38 and if you pass the test, did you purchase today, yeah, ok, cool, then we are going to take your name, we are going to stick in this list,
0:43 there is a couple of drawbacks, one is this is basically impossible to condense down
0:49 to something you can pass as an argument or simply assign a variable to, the other one is it's just kind of verbose and you have to say all the steps,
0:58 telling the runtime, the implementation exactly what to do. We can use something called a list comprehension to simplify this
1:05 and condense it down to what is equivalent to a single line of Python, so then we can more easily assign it to variables,
1:13 pass it to functions, things like that. So we can write the exact same code like this,
1:18 we can say paying_username= [ ] just like we are going to define a list,
1:22 what goes in there is not static data, in fact we put this expression it has three parts, the first part is the projection, remember,
1:28 we are given a set of users and we want just the names, we kind of got to think ahead a little bit,
1:33 this is a little bit annoying about it but you have to imagine well if I am going to name the customers what variable will I use
1:39 to name each and everyone of them as if this were a loop, we could say if that was going to be you then I would like to name,
1:45 so u.name goes into projection. Then you write the source, and it always goes like for something in some set,
1:52 so here we have for u in get_active_customers(). And then finally the test or filter, so we say if and then we just put our test here
1:59 our test was if the last purchase was today, so we say if you.last_purchase==today, done.
2:06 And the way I've written it it's not that much shorter on the screen but because it's a single expression you can do things like
2:15 pass it the functions as single arguments, or sort of combine them and just have a lot more flexibility.
2:20 You also see as we move onto the next evolution of this concept, the generator expressions, then you actually get even more benefit,
2:29 there is actually performance benefits or consequences depending how you use it.