What Is the map() Function?
In this lesson, you’ll see that
map() is a built-in function that is one of the functional programming primitives (or building blocks) available in Python. It’s useful in a number of contexts.
map() takes two arguments: an iterable (like a list) and a function. It then applies that function to all of the elements in the iterable. It outputs an iterator of items that are the result of the function called on the items in the first iterator.
00:11 You’re usually going to get a list object back instead of an iterable—or, an iterator. So, this is maybe something you’ll have to adjust for, but that shouldn’t be too hard. Let’s take a look at the docstring here.
this bit here,
using arguments from each of the iterables. So, basically, we’re passing in an iterable, like a list of something, and then
map() is going to apply our function on each item in this list and it’s going to create an output stream, or an output iterator of items that are the results of this function
func called on one of the items.
00:55 And we’re stopping once we’re done here. And actually, I think you can pass a number of iterables here and they will all kind of be chained together. We’re not going to be doing that in this tutorial. Okay.
01:05 So, I know this stuff sounds super confusing. The first time I read this, I was like, “Okay, I have no idea what this will be good for and when I would ever use this,” and yeah, I don’t know. It made me feel pretty stupid.
01:19 So what I’m going to do next is I’m going to try and make sure you get some real examples of how this would work, how this would be useful. So, I just wanted to show you this data set that we used in previous installments
of the series. We have this data set of scientists, these are all
namedtuple objects so that they’re immutable. The whole thing is actually stored inside a tuple so that the whole structure is immutable. That’s why I didn’t use a plain list, for example.
01:51 And by immutable, it just means, you know, we can’t reach in and modify these objects. If we wanted to modify one, we’d have to make a copy, and that way we can trace these changes and we can make sure that this list is always going to be the same.
Become a Member to join the conversation.