list comprehension with multiple conditions (python)

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"

Leave a Comment