Understand the Concept of Filtering

00:00 Welcome to this lesson, where you’ll dive into the fascinating world of filtering iterables. As a reminder, an iterable is any object that can be looped over, such as a list, a string, and a generator. Now let’s clarify what filtering is.

00:16 Filtering is a process of selecting specific elements from an iterable based on a given condition. Let’s understand this better with an example.

00:27 Here you have a list of integers from -2 to 2 named numbers. Now, let’s say you want to extract only the positive numbers from this list.

00:37 To do this, you can define a function named extract_positive() that takes a list as its input. Inside this function, you create an empty list called positive_numbers.

00:49 Then you loop through each number in the input list using a for loop For each number, you check if it’s greater than 0 or not using an if statement. If it is, you append it to the positive_numbers list.

01:03 Now this if statement is your filtering condition. Finally, once all the numbers have been checked, you return the positive_numbers lists.

01:13 When you run the extract_positive() function with the numbers list as its input, you get 1 and 2 as a result. So -2, -1, and 0 have been filtered out since their filtering condition evaluated as False.

01:30 1 and 2 have not been filtered out since their filtering condition translates to True since, well, they are bigger than 0.

01:40 In other words, the negative numbers and 0 got filtered out.

01:46 To summarize what you’ve learned so far, a filtering condition is a statement that evaluates to either True or False based on a given criterion. For example, the if statement from before, if number > 0, is a filtering condition.

02:01 It evaluates to True or False depending on whether number is greater than 0 or not. The members of the input get disqualified if their filtering condition is False.

02:12 For example, -2, -1, and 0 got disqualified in the example since their filtering condition evaluated as False. Congratulations, you now know the essence of filtering. In the next lesson, you’ll explore how to use the filter() function in Python to filter iterables.

Become a Member to join the conversation.