Consider this example:
l = [1, 2, 3, 4, 5]
for values in l:
if values == 1:
print('yes')
elif values == 2:
print('no')
else:
print('idle')
Rather than print
ing the results, I want to use a list comprehension to create a list of results, like ['yes', 'no', 'idle', 'idle', 'idle']
.
How can we represent the elif
logic in a list comprehension? Up until now, I have only used if
and else
in list comprehension, as in if/else in a list comprehension.
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']