vashts85
vashts85

Reputation: 1147

list comprehension with multiple conditions (python)

The following code works in Python

var=range(20)
var_even = [0 if x%2==0 else x for x in var]
print var,var_even

However, I thought that the conditions need to be put in the end of a list. If I make the code

var_even = [0 if x%2==0 for x in var]

Then it won't work. Is there a reason for this?

Upvotes: 1

Views: 3488

Answers (2)

Haifeng Zhang
Haifeng Zhang

Reputation: 31885

0 if x%2==0 the syntax is value1 if conditionX else value2 , what it does is if conditionX is true, it returns value1, otherwise it returns value2. You cannot use it if you want to get the event numbers from the list, you always return value 0 if it is an even number and you miss the else clause

You can achieve it like this:

>>> var_even = [x for x in var if x % 2 ==0]
>>> var_even
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Alternatively, you can use filter:

>>> even_numbers = filter(lambda x: x % 2 == 0, var)
>>> list(even_numbers)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Upvotes: 1

user2357112
user2357112

Reputation: 280237

There are two distinct but similar-looking syntaxes involved here, conditional expressions and list comprehension filter clauses.

A conditional expression is of the form x if y else z. This syntax isn't related to list comprehensions. If you want to conditionally include one thing or a different thing in a list comprehension, this is what you would use:

var_even = [x if x%2==0 else 'odd' for x in var]
#             ^ "if" over here for "this or that"

A list comprehension filter clause is the if thing in elem for x in y if thing. This is part of the list comprehension syntax, and it goes after the for clause. If you want to conditionally include or not include an element in a list comprehension, this is what you would use:

var_even = [x for x in var if x%2==0]
#                          ^ "if" over here for "this or nothing"

Upvotes: 4

Related Questions