Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if else in a list comprehension [duplicate]

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 ifelse like this in a list comprehension?

like image 757
user225312 Avatar asked Dec 10 '10 06:12

user225312


People also ask

Can I use if-else in list comprehension Python?

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.

Does list comprehension make a copy?

Using list comprehension. The method of list comprehension can be used to copy all the elements individually from one list to another.

Can you do Elif in list comprehension?

You can't use elif in list comprehension because it's not part of the if-else short-expression syntax in Python.

Is list comprehension faster than for loop?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.


2 Answers

>>> 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.

like image 149
user225312 Avatar answered Oct 02 '22 19:10

user225312


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 
like image 39
arboc7 Avatar answered Oct 02 '22 19:10

arboc7