The map() Function vs Generator Expressions – Real Python (original) (raw)
In the previous lesson, you covered how to use the map()
function in Python in order to apply a function to all of the elements of an iterable and output an iterator of items that are the result of that function being called on the items in the first iterator.
In this lesson, you’ll see how the map()
function relates to list comprehensions and generator expressions. You’ll learn that using them is (arguably) more Pythonic than relying on plain map()
calls.
00:00 Now, of course, you might be thinking, “Uh, you know what? This looks, kind of… not anything like the usual Python code that I see, or that I would like to write.” And I totally get that. Like, honestly, I would probably not recommend that you write code that looks like this, because it gets confusing.
00:16 It’s very hard for people who are new to Python to understand what’s going on, and it’s kind of a different mindset that you’re in when you’re writing stuff like that.
00:24 So, actually, what you would probably do to make this more Pythonic is you would define a list comprehension, so, something like this. Again, I’m going to define the same fields here—x.name—and then I’m going to add this computed property called 'age' […] x.born.
00:44 And… then, I would just do this for any x in scientists.
00:54 All right! There, you have it. That’s our list comprehension. So, you would do the same thing—typically, you would do it with a list comprehension, because that just kind of gives you a more Pythonic syntax. Now, this isn’t equivalent yet, so we need to make some small changes here. First of all, I would probably do this—if I wanted to make it as close to the map() call, I would do this with a generator expression that I just passed to this tuple() function.
01:33 And then—okay, I can tell we’re doing this in one line now. Then, we can pprint() it—pretty-print it. So, this is from the pprint module, if you haven’t seen the first installments of the series.
01:44 We can just be pprint() it out, and this is what it looks like and we get the same result. So, I would rather write something like this—a generator expression—and then post-process that, or something like this, than this map() call that we had up here, but—it’s kind of personal preference? And both of them, it’s good to know about these things, right?
02:09 It’s good to know how these functional programming principles that are available in most other programming languages—how they correspond to the Python specifics of having a list comprehension here,