if else in a list comprehension [duplicate] if else in a list comprehension [duplicate] python python

if else in a list comprehension [duplicate]


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


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

And for a reward, here is the comment, I wrote to remember this the first time I did this error:

Python's conditional expression is a if C else b and can't be used as:

[a for i in items if C else b]

The right form is:

[a if C else b for i in items]

Even though there is a valid form:

[a for i in items if C]

But that isn't the same as that is how you filter by C, but they can be combined:

[a if tC else b for i in items if fC]


matomo