Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k 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 (106k 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]

Related questions

0 votes
1 answer
0 votes
2 answers
asked Sep 17, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...