Skip to main content

9.10) Lists Comprehension With A Filter


You can combine a list comprehension with an if statement to filter out the elements of the input sequence. For example, we can select only even elements of the list L:

>>> L=range(1,11)
>>> [i for i in L if i%2 ==0]
[2, 4, 6, 8, 10]

In the example above, i%2 == 0 checks if the remainder of a division by two is 0. If that’s the case, you know the number is even (divisible by two). The variable i is assigned values in the list L only if they are even values.

You can combine the filtering with an operation:

>>> [i**2 for i in range(1,11) if i%2 ==0]
[4, 16, 36, 64, 100]

And you can even combine two loops within the list comprehension. So you can flatten a list, for example:

>>> matrix = [[1,2,3], [4,5,6]]
>>> [x for row in matrix for x in row]
[1, 2, 3, 4, 5, 6]