If else in list comprehension Python

To use if else statement with Python list comprehension we need to use the following syntax: [x if condition else g(x) for x in sequence]

The example below shows: if else in list comprehension:

row = [4, 5, 6, 7, 12, 34]
[el if el < 10 else el % 10 for el in row]

The code above will extract last digit from any number or the number itself when it's less than 10.

if comprehension example

Alternatively we can use the following syntax: [f(x) for x in sequence if condition]:

[x for x in range(1, 15) if x % 11 == 0]

result:

[11]

if else or - in comprehension

Example of if else in list comprehension plus Python or:

[x for x in range(1, 15) if x % 5 == 0 or x % 7 == 0]

result:

[5, 7, 10, 14]

elif in list comprehension

There are multiple ways to add elif to list comprehension in Python. One way is by converting the if else statament like:

for v in l:
    if v == 0 :
        print '0'
    else:
        if v < 0:
            print 'negative'
        else:
            print 'positive'

to:

['0' if v == 0 else 'positive' if v < 0 else 'negative' for v in l]