Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Replace filter() With a List Comprehension

00:00 In this lesson, you’ll briefly hear about list comprehensions and then learn how you can replace the filter() function with the list comprehension. List comprehensions are a concise way of creating a new list by iterating over an existing list and applying a transformation or condition to each element.

00:19 They allow you to write shorter and more readable code that is easier to understand and maintain. Here is an example. You have a list of numbers. Some of them are above a hundred, and some aren’t.

00:31 You only want to keep the ones above a hundred. You have this list comprehension here that keeps the numbers above a hundred in the above_hundred list. [number for number in numbers if number > 100].

00:49 So the list comprehension created a new empty list named above_hundred. Then it loops over every number in the numbers list and appended the ones that were above a hundred to above_hundred For the syntax, first you need to specify what you want to do with the items that you’re looping over. Here, you’re just appending them, so it’s just number.

01:11 Then you loop over your iterable: for number in numbers. Then it’s optional to add an if statement. Here it’s if number > 100.

01:24 Here you can see what’s inside of above_hundred. It’s 103, 105, and 160, so you got rid of 10 and 99.

01:34 This sounds exactly like what you have been doing in the previous lessons, right? You created a filtering condition—in this case if number > 100and filtered 10 and 99 and kept the items you actually needed, which were 103, 105, and 160.

01:51 This is how you can use list comprehensions to filter iterables instead of filter().

02:00 Let’s look at an example that you’ve done before, extracting even numbers from the list. On the right, you can see your previous version with filter().

02:09 You have a predicate function, is_even(), that takes a number and returns True if the number is even and False if not, and then you used filter() with is_even and numbers and extracted the even numbers. On the left, you’re doing it with a list comprehension, even_numbers = [number for number in numbers if number % 2 == 0].

02:35 So you’re looping through numbers and keeping the ones that are even using the same predicate function as before, and your final result is exactly the same: 10, 6, and 50.

02:49 This is how you can use list comprehensions instead of the filter() function to filter iterables.

Become a Member to join the conversation.