Replace filter() With a List Comprehension
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.
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
[number for number in numbers if number > 100].
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
This sounds exactly like what you have been doing in the previous lessons, right? You created a filtering condition—in this case
if number > 100—and filtered
99 and kept the items you actually needed, which were
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
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].
Become a Member to join the conversation.