I have a list l
:
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.
I tried
[x+1 for x in l if x >= 45 else x+5]
But it gives me a syntax error. How can I achieve an if
– 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]
Do-something if <condition>
, else do-something else.