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?
b. if..else in List Comprehension in Python. You can also use an if-else in a list comprehension in Python. Since in a comprehension, the first thing we specify is the value to put in a list, this is where we put our if-else.
Using list comprehension. The method of list comprehension can be used to copy all the elements individually from one list to another.
You can't use elif in list comprehension because it's not part of the if-else short-expression syntax in Python.
Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.
>>> 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.
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
Where the 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 expression
):
for x in l: if x>=45: x+1 else: x+5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With