Given a list comprehension you can append one or more if conditions to filter values.
[ for in if ]For each in ; if evaluates to True, add [usually a function of ] to the returned list.
For example, this can be used to extract only even numbers from a sequence of integers:
[x for x in range[10] if x % 2 == 0] # Out: [0, 2, 4, 6, 8]Live demo
The above code is equivalent to:
even_numbers = [] for x in range[10]: if x % 2 == 0: even_numbers.append[x] print[even_numbers] # Out: [0, 2, 4, 6, 8]Also, a conditional list comprehension of the form [e for x in y if c] [where e and c are expressions in terms of x] is equivalent to list[filter[lambda x: c, map[lambda x: e, y]]].
Despite providing the same result, pay attention to the fact that the former example is almost 2x faster than the latter one. For those who are curious, this is a nice explanation of the reason why.
Note that this is quite different from the ... if ... else ... conditional expression [sometimes known as a ternary expression] that you can use for the part of the list comprehension. Consider the following example:
[x if x % 2 == 0 else None for x in range[10]] # Out: [0, None, 2, None, 4, None, 6, None, 8, None]Live demo
Here the conditional expression isn't a filter, but rather an operator determining the value to be used for the list items:
if elseThis becomes more obvious if you combine it with other operators:
[2 * [x if x % 2 == 0 else -1] + 1 for x in range[10]] # Out: [1, -1, 5, -1, 9, -1, 13, -1, 17, -1]Live demo
If you are using Python 2.7, xrange may be better than range for several reasons as described in the xrange documentation.
[2 * [x if x % 2 == 0 else -1] + 1 for x in xrange[10]] # Out: [1, -1, 5, -1, 9, -1, 13, -1, 17, -1]The above code is equivalent to:
numbers = [] for x in range[10]: if x % 2 == 0: temp = x else: temp = -1 numbers.append[2 * temp + 1] print[numbers] # Out: [1, -1, 5, -1, 9, -1, 13, -1, 17, -1]One can combine ternary expressions and if conditions. The ternary operator works on the filtered result:
[x if x > 2 else '*' for x in range[10] if x % 2 == 0] # Out: ['*', '*', 4, 6, 8]The same couldn't have been achieved just by ternary operator only:
[x if [x > 2 and x % 2 == 0] else '*' for x in range[10]] # Out:['*', '*', '*', '*', 4, '*', 6, '*', 8, '*']See also: Filters, which often provide a sufficient alternative to conditional list comprehensions.
You can’t use elif in list comprehension because it’s not part of the if-else short-expression syntax in Python.
Get the same logic with chaining:
if b1: a elif b2: b else: cBecomes
a if b1 else b if b2 else cExample list comprehension if elif else in Python
Simple example code.
[print['Hi'] if num == 2 and num % 2 == 0 else print['Bye'] if num % 2 == 0 else print[ 'buzz'] if num == 5 else print[num] for num in range[1, 6]]Output:
Note: it is totally discouraged to use such unreadable list comprehensions in real-life projects!
Source: stackoverflow.com
Another Example
Python’s conditional expressions were designed exactly for this sort of use-case:
l = [1, 2, 3, 4, 5] res = ['Y' if v == 1 else 'N' if v == 2 else 'Idle' for v in l] print[res]Output: [‘Y’, ‘N’, ‘Idle’, ‘Idle’, ‘Idle’]
Do comment if you have any doubts and suggestions on this Python list tutorial.
Note: IDE: PyCharm 2021.3 [Community Edition]
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.
There’s no direct use “elif” construct ist comprehension conditionals, but it can be simulated with nested if/else statements.
Common if-else syntax
['Yes' if v == 1 else 'No' for v in l]The ternary form of the if/else operator doesn’t have an ‘elif’ built-in, but you can simulate it in the ‘else’ condition:
['Yes' if v == 1 else 'No' if v == 2 else '0' for v in l]Python example elif in the list comprehension
Simple example code use list comprehension is you are going to create another list from the original.
l = [1, 2, 3, 4, 5] res = ['Yes' if v == 1 else 'No' if v == 2 else '0' for v in l] print[res]Output:
Another Example code
Creating product reviews that take values from 1 to 5 and create a list with three categories:
- Good >= greater or equal to 4
- Neutral = if the review is 3
- Negative < if the review is less than 3
Output: [‘Good’, ‘Bad’, ‘Bad’, ‘Good’, ‘Good’, ‘Bad’]
Do comment if you have any doubts and suggestions on this Python List topic.
Note: IDE: PyCharm 2021.3 [Community Edition]
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.
This tutorial will explain multiple ways to perform list comprehension with the if ... else statement in Python. A list comprehension is a short and syntactic way to create a list based on an existing list. It is usually used to create a new filtered or changed list from a current list.
For example, we have a python list ['Ali','Mark', None, 'Sara', None, 'Rahul'] and we want to create a new list ['Ali','Mark', '', 'Sara', '', 'Rahul'], we can do it by using list comprehension.
Python if ... else List Comprehension
The below example code demonstrates how we can create a changed list from the existing list using list comprehension with the if ... else statement:
my_list = ['Ali','Mark', None, 'Sara', None, 'Rahul'] new_list = [str[x.strip[]] if x is not None else '' for x in my_list] print[new_list]Output:
['Ali', 'Mark', '', 'Sara', '', 'Rahul']The general syntax of list comprehension in Python with if ... else is:
[f[x] if condition else g[x] for x in list]If condition is true for the list element x, f[x], any applicable function, is applied to the element; otherwise, g[x] will be applied.
Example code:
my_list = ['Ali','Mark', None, 'Sara', None, 'Rahul'] new_list = [x.upper[] if x is not None else '' for x in my_list] print[new_list]Output:
['ALI', 'MARK', '', 'SARA', '', 'RAHUL']DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.