Home Tutorials How to use Filtering Elements in List Comprehension in Python

How to use Filtering Elements in List Comprehension in Python

How to use Filtering Elements in List Comprehension in Python
find Python moduels

Conditional statements can use to filter data in Python list comprehensions. You learned how to create a list of even squares using filtering in this session

Filtering Elements in List Comprehension in Python

Except that only even squares return, the data returned is the same as previously. This operation’s logic contains in a single line.

The following is an example of a list comprehension with a filter or conditional statement:

if x percent 2 == 0, even squares = [x * x for x in range(10)]

This list comprehension will write using traditional for loops in the future session.

I’ve modified my example here by adding filtering, and as you can see, it’s extremely identical to the prior one. You’ll find that all of the parts you’re used to are still present.

We’ve got our output list of values, the expression we calculated, and this for the in part that we’re going to run.

This fresh material at the end is when the filtering takes place. In this scenario, we’re calculating the same set of values as before, but we’re only keeping the ones when this condition is True.

In case you’re unfamiliar with the modulo (percent) operator, it divides two numbers and returns the remainder. As a result, if I go 31% 2, the remaining is 1 because it’s an odd number. We can’t divide it evenly by two, thus the remainder is one. And if I go 30 percent 2, the remainder will be zero.

I’m using it here in this filtering expression to ensure that the values in this even squares list are all equal. As a result, this is a fantastic technique to locate

For that, you can simply use the modulo operator. So, let’s have a look at the output that we’ve generated so far. As you can see, the previous list of squares has filtered down to only contain the even squares. Remember that this is what we had before the filtering, which includes odd numbers which are now all gone because we filtered them out using this if the section of the list comprehension.

Let’s see how this affects our loop template behind the scenes—or how we can turn this into a regular loop template behind the scenes.


Please enter your comment!
Please enter your name here