0 votes
1 view
in Python by (32.3k points)
edited by

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?

1 Answer

0 votes
by (76.5k points)

You can write the if-else statement in list comprehension by the following way:-

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

>>> [x+1 if x >= 45 else x+5 for x in l]

...