I have a list
l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5.
[x+1 for x in l if x >= 45 else x+5]
But it gives me a syntax error. How can I achieve an
else like this in a list comprehension?
>>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1] >>> [x+1 if x >= 45 else x+5 for x in l] [27, 18, 46, 51, 99, 70, 48, 49, 6]
<condition>, else do-something else.
The reason you're getting this error has to do with how the list comprehension is performed.
Keep in mind the following:
[ expression for item in list if conditional ]
Is equivalent to:
for item in list: if conditional: expression
expression is in a slightly different format (think switching the subject and verb order in a sentence).
Therefore, your code
[x+1 for x in l if x >= 45] does this:
for x in l: if x >= 45: x+1
However, this code
[x+1 if x >= 45 else x+5 for x in l] does this (after rearranging the
for x in l: if x>=45: x+1 else: x+5