1

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?

vashts85
  • 1,069
  • 3
  • 14
  • 28
  • When you want to use only an `if` condition in your list comprehension (not with `else`) you need to put it after `for` if you want to use it with else you should put them before `for`. – Mazdak Jul 15 '16 at 18:23
  • 1
    Conditional expressions must have an `else`. See the [docs](https://docs.python.org/2/reference/expressions.html#conditional-expressions). – martineau Jul 15 '16 at 18:24
  • `(0 if x%2 == 0 else x)` is a [conditional expression](http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator). It is not part of the list comprehension. – kennytm Jul 15 '16 at 18:25

2 Answers2

4

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"
user2357112
  • 260,549
  • 28
  • 431
  • 505
1

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]
Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125