Fix Python – if else in a list comprehension [duplicate]

Question

Asked By – user225312

Given a list xs:

xs = [22, 13, 45, 50, 98, 69, 43, 44, 1]

For numbers above 45 inclusive, add 1; and for numbers less than 45, add 5.

Now we will see solution for issue: if else in a list comprehension [duplicate]


Answer

>>> xs = [22, 13, 45, 50, 98, 69, 43, 44, 1]
>>> [x+1 if x >= 45 else x+5 for x in xs]
[27, 18, 46, 51, 99, 70, 48, 49, 6]

Do-something if <condition>, else do-something else.

This question is answered By – user225312

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0