What Is the filter() Function?
In this lesson, you’ll learn that
filter() is one of the functional programming primitives (or building blocks) available in Python and that it’s useful in a number of contexts.
You’ll see how you can use
filter() to play with your data set. You’ll write a filter expression to see which items in your data set meet particular criteria.
filter() takes another function object, and you can define a function object inline with
filter() function is built-in and it has maybe a slightly complicated docstring. It says here, the
filter() function returns […]
yielding those items of iterable for which function(item) is true.
If function is None, return the items that are true. Okay. What does that mean?
What I want to do now is I want to write a
filter() expression that gives me all of the scientists in this list, or actually, gives me a new list of scientists that have won the Nobel Prize. Or, the opposite, right?
Here, I’m going to say
lambda x, so, this is the object that will be passed in. So
x, I want this to return
False depending on whether or not the
nobel flag is set to
I can go here and I can say
x.nobel is True. So, if you’re wondering how a
lambda works, it’s basically a one-line function, like a shortcut for defining a function in Python. So, you can put arguments, and then you have one expression that gets evaluated.
You don’t have to do
return or anything—that’s automatic. And it will just evaluate this expression and return it back out of the lambda function. In this case, I’m just comparing
I could have shortened that and just said
x.nobel, but honestly, I think this is nicer because it actually makes sure we’re returning a boolean and I think that’s the better way to do it. In this case, I would say—all right, we’re checking here and we’re passing in an
iterable, which is the list of scientists here. Okay.
02:21 What do you think is going to happen when I run this? Oh, okay! So, depending on whether you’re running this on Python 2 or 3, you’re going to see a different result here. On Python 2, this will have created a list object containing all of these filtered scientists, or the scientists that passed this test here, so this is like a test function.
Let’s call this
fs for filtered scientists, and then we can just say
next(fs) and that’s going to give me all of these filtered scientists. And you can see here, this only contains scientists that had
.nobel set to
True, and now we’re hitting a
StopIteration exception, and we’re at the end of that.
Become a Member to join the conversation.