The list comprehension syntax allows adding one or more if
clauses to a list comprehension after for
clause(s).
You can use the if
clause in a list comprehension for filtering the items in the list that the comprehension generates. The items that are included in the final list are the ones for which the "if
" clause evaluates to True
.
#Syntax
You can use any of the following syntax:
new_list = [expression for item in iterable if condition] new_list = [expression for item in iterable if condition_1 if condition_2 ... if condition_n] new_list = [expression for item_1 in iterable_1 if condition_1 ... for item_n in iterable_n if condition_n]
Where:
expression
is the expression that will be evaluated and included in the resulting list;item
is the variable representing the current element in theiterable
;iterable
is a collection of elements to iterate over;if condition
is an optional condition that filters the items in theiterable
before they're transformed by theexpression
.
A list comprehension has at least one for
clause, which can be followed by zero or more for
and/or if
clauses.
#Examples
For example, consider the following list comprehension that generates a list of squares of the numbers from 1
to 5
:
squares = [num ** 2 for num in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
You can filter this list to only include the squares of even numbers by adding an "if
" clause to the list comprehension, for example, like so:
squares = [num ** 2 for num in range(1, 6) if num % 2 == 0]
print(squares) # [4, 16]
This is equivalent to:
squares = []
for num in range(1, 6):
if num % 2 == 0:
squares.append(num ** 2)
print(squares) # [4, 16]
Either of these create a new list of squares that only includes the squares of the even numbers, because the "if
" clause "x % 2 == 0
" only evaluates to True
for the even numbers in the range from 1
to 5
.
In a list comprehension, you can also use if-else
syntax in the expression part of the comprehension (i.e. before the main for
clause). Note that this is different from the if
clause, which appears after the for
clause(s).
Using Multiple if
Clauses:
It is possible to include multiple "if
" clauses in a list comprehension to filter the items based on multiple conditions:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_nums = [n for n in nums if n > 5 if n % 2 == 0]
print(filtered_nums) # [6, 8, 10]
In this example, the comprehension creates a new list, and fills it with the numbers that meet both of the following conditions:
n > 5
— numbers that are greater than5
, and;n % 2 == 0
— numbers that are even.
It works by filtering out the numbers that are less than 5
and not divisible by 2
, resulting in [6, 8, 10]
.
This is the same as using the logical and
operator:
# ...
filtered_nums = [n for n in nums if n > 5 and n % 2 == 0]
# ...
These are equivalent to:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_nums = []
for n in nums:
if n > 5 and n % 2 == 0:
filtered_nums.append(n)
print(filtered_nums) # [6, 8, 10]
You can, of course, also use the logical or
operator, for example, like so:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_nums = [n for n in nums if n > 5 or n < 2]
print(filtered_nums) # [1, 6, 7, 8, 9, 10]
This will filter out numbers greater than 5
or less than 2
, resulting in [1, 6, 7, 8, 9, 10]
.
It's important to note that the order of the "if
" clauses in the list comprehension is important. The comprehension is evaluated from left-to-right, so the items are first filtered based on the condition in the first "if
" clause, and then the remaining items are further filtered based on the condition in the second "if
" clause, and so on.
Using if
With Multiple for
Clauses:
A list comprehension can also have multiple for
clauses, which can be followed by zero or more if
clauses.
For example, consider the following list comprehension that combines the elements of two lists if they are not equal:
points = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print(points) # [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
This is equivalent to:
points = []
for x in [1, 2, 3]:
for y in [3, 1, 4]:
if x != y:
points.append((x, y))
print(points) # [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.