Skip to main content
Noble Desktop/3 min read

Filters in Python

Filtering Approaches

filter() Function

filter(predicate, iterable) returns iterator of matching items.

List Comprehension

[x for x in lst if condition] — more Pythonic for most cases.

Pandas Boolean Mask

df[df['col'] > 100] for DataFrame filtering.

itertools.filterfalse

Returns items where predicate is False — opposite of filter.

Master Python at Noble Desktop

Noble Desktop's Python Programming Immersive covers AI APIs, data analysis, and modern Python development.

In this video, we're going to look at how to use Filters in Python

Video Transcription

Hi, my name is Art. I teach Python at Noble Desktop. I hope you watched my other videos because in this video I'm going to explain how to use loops and if statements to filter something.

Let me give an example. Suppose I have a list of numbers: 1,2, 3,4, and many fives (5,5, 5,5, 5). Suppose my job is to get all the fives and maybe count them. How would I do that?

It's pretty simple, but let's break it down into steps. First, we need to iterate through the list. We can do this with a loop or number (or any other variable name) in numbers. Let's print that and see what n is. It's pretty much every number.

Now, in our example, we're looking for fives. How will Python know that the number is five? Python can't just take a look, since the list could be really long (thousands, tens of thousands, or even millions of items). We need to compare.

We can do this with an if statement. We need to use an equal comparison operator (==) and say if n == 5. Since after the colon, we need to use indentation, we can move the print statement within the scope of the if statement. We got all the fives!

Now we need to count them. We need some kind of counter, so let's create a new variable and call it "counter". It will start at zero since we haven't seen any fives yet.

What should we do when the if statement returns true? We need to take the counter and increase it by one. We can print the counter outside of the loop. We got five fives.

There is a shorter syntax that means the same thing. We can use "counter += 1". We can also create a new list to store the fives. Let's call it "fives".

We can use the append method to take that object and add it to the end of the list. At the end of the day, if you print "fives", you'll see that the new list contains just the fives. That's how you filter something.

Thanks for watching! In my other video, I'm going to show you how to sort a string.