How to Use a Conditional Expression (Expression with If and Else) in a List Comprehension

How can I use a conditional expression (expression with if and else) in a list comprehension?

x if y else z is the syntax for the expression you're returning for each element. Thus you need:

[ x if x%2 else x*100 for x in range(1, 10) ]

The confusion arises from the fact you're using a filter in the first example, but not in the second. In the second example you're only mapping each value to another, using a ternary-operator expression.

With a filter, you need:

[ EXP for x in seq if COND ]

Without a filter you need:

[ EXP for x in seq ]

and in your second example, the expression is a "complex" one, which happens to involve an if-else.

if/else in a list comprehension

You can totally do that. It's just an ordering issue:

[f(x) if x is not None else '' for x in xs]

In general,

[f(x) if condition else g(x) for x in sequence]

And, for list comprehensions with if conditions only,

[f(x) for x in sequence if condition]

Note that this actually uses a different language construct, a conditional expression, which itself is not part of the comprehension syntax, while the if after the for…in is part of list comprehensions and used to filter elements from the source iterable.


Conditional expressions can be used in all kinds of situations where you want to choose between two expression values based on some condition. This does the same as the ternary operator ?: that exists in other languages. For example:

value = 123
print(value, 'is', 'even' if value % 2 == 0 else 'odd')

if else in a list comprehension

>>> xs = [22, 13, 45, 50, 98, 69, 43, 44, 1]
>>> [x+1 if x >= 45 else x+5 for x in xs]
[27, 18, 46, 51, 99, 70, 48, 49, 6]

Do-something if <condition>, else do-something else.

using conditional with list comprehension

You need the else in the list comprehension because it needs to know the value to return in the result for every item being iterated over. There's no automatic default to return the item itself. So the conditional expression needs to provide values when the condition is true and also when it's false.

This isn't necessary in the for loop because it's not returning anything, it's executing statements. You're modifying the list in place in the if statement, and not doing anything at all when the condition fails. But there's no such thing as "not doing anything at all" in a conditional expression.

If you want to return the value unchanged, use else x -- there's no need to add 0.

How can I use if/else in list comprehensions?

You are missing the x before if:

lst = [x if x % 2 == 0 else 'odd' for x in range(11)]

The Python conditional expression syntax has to have both the 'true' and the 'false' expressions present, so true_expr if condition else false_expr, where one of true_expr or false_expr will be evaluated based on the truth value of the condition expression.

Demo:

>>> [x if x % 2 == 0 else 'odd' for x in range(11)]
[0, 'odd', 2, 'odd', 4, 'odd', 6, 'odd', 8, 'odd', 10]

Note that using a conditional expression doesn't filter, it always produces output. That's great for the per-iteration expression side of the list comprehenion syntax, but if you wanted to filter the input list and remove odd values altogether, then use a if condition test after the for ... in ... loop:

>>> [x for x in range(11) if x % 2 == 0]  # filtering, only even numbers
[0, 2, 4, 6, 8, 10]

Multiple if/else on list comprehensions

What you have here is not a list comprehension with conditionals (which filters out some elements of the comprehension), but a post-expression conditional of the form

x = A if (condition) else B

This assigns A if (condition) is true, otherwise it assigns B. (The syntax is a little confusing to look at, it must be admitted, but even Python is not always perfect.) You've managed to stack two of these inside each other, like this:

i**2 if i == 10 else (i-5 if i < 7 else i+5)

Reading from the right: The expression (i-5 if i < 7 else i+5) will give you i-5 if i<7, else you get i+5. Whatever value this is, it is included in the comprehension whenever i==10 is false (so, for the first and third list element).

Note that this construction has nothing to do with a list comprehension; you can use it anywhere (as long as i is defined).

i = 31
x = i**2 if i == 10 else (i-5 if i < 7 else i+5)

For comparison, here is a real conditional list comprehension: The comprehension will remove values that are equal to 10, leaving you with two elements in the result. I think this is the construction you set out to understand.

num3 = [ i**2 for i in num1 if i != 10 ]

Syntax error when using if else statements in list comprehension

word[1:] + word[0] + "ay" if word not in ",!?" else word This is a conditional expression also know as Ternary Operators and
you must put expression at the left of a for loop statement and if condition at the right side of a for loop statement in a list comprehension.

return " ".join(
[word[1:] + word[0] + "ay" if word not in ",!?" else word for word in text.split()]
)

List comprehension with if statement

You got the order wrong. The if should be after the for (unless it is in an if-else ternary operator)

[y for y in a if y not in b]

This would work however:

[y if y not in b else other_value for y in a]

Is it possible to use 'else' in a list comprehension?

The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

So for your example,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
for index in xrange(15))


Related Topics



Leave a reply



Submit