`elif` in list comprehension conditionals

PythonList ComprehensionConditional Operator

Python Problem Overview


Can we use elif in list comprehension?

Example :

l = [1, 2, 3, 4, 5]

for values in l:
    if values==1:
        print 'yes'
    elif values==2:
        print 'no'
    else:
        print 'idle'

Can we include the elif in our list comprehension, in a similar fashion to the code above?

For example, an answer like:

['yes', 'no', 'idle', 'idle', 'idle']

Up until now, I have only used if and else in list comprehension.

Python Solutions


Solution 1 - Python

Python's conditional expressions were designed exactly for this sort of use-case:

>>> l = [1, 2, 3, 4, 5]
>>> ['yes' if v == 1 else 'no' if v == 2 else 'idle' for v in l]
['yes', 'no', 'idle', 'idle', 'idle']

Solution 2 - Python

>>> d = {1: 'yes', 2: 'no'}
>>> [d.get(x, 'idle') for x in l]
['yes', 'no', 'idle', 'idle', 'idle']

Solution 3 - Python

You can, sort of.

Note that when you use sytax like:

['yes' if v == 1 else 'no' for v in l]

You are using the ternary form of the if/else operator (if you're familiar with languages like C, this is like the ?: construct: (v == 1 ? 'yes' : 'no')).

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 'idle' for v in l]

This is like saying:

for v in l:
    if v == 1 :
        print 'yes'
    else:
        if v == 2:
            print 'no'
        else:
            print 'idle'

So there's no direct 'elif' construct like you asked about, but it can be simulated with nested if/else statements.

Solution 4 - Python

You can use list comprehension is you are going to create another list from original.

>>> l = [1, 2, 3, 4, 5]
>>> result_map = {1: 'yes', 2: 'no'}
>>> [result_map[x] if x in result_map else 'idle' for x in l]
['yes', 'no', 'idle', 'idle', 'idle']

Solution 5 - Python

Another easy way is to use conditional list comprehension like this:

l=[1,2,3,4,5]
print [[["no","yes"][v==1],"idle"][v!=1 and v!=2] for v in l]

gives you the correct anwer:

['yes', 'no', 'idle', 'idle', 'idle']

Solution 6 - Python

Maybe you want this:

l = [1, 2, 3, 4, 5] 

print ([['idle','no','yes'][2*(n==1)+(n==2)] for n in l])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionselfView Question on Stackoverflow
Solution 1 - PythonRaymond HettingerView Answer on Stackoverflow
Solution 2 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - Pythonmathematical.coffeeView Answer on Stackoverflow
Solution 4 - PythonSan4ezView Answer on Stackoverflow
Solution 5 - PythonStefan GruenwaldView Answer on Stackoverflow
Solution 6 - PythonRatnesh KushwahaView Answer on Stackoverflow