0

I'm trying to create a list with even numbers showing as they are and odd numbers showing as "odd".

Here is the code I am trying.

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

I expected to get something like this

[0, "odd", 2, "odd", 4, "odd", 6, "odd", 8, "odd", 10]

But I keep getting SyntaxError exception:

>>> lst = [if x % 2 == 0 else 'odd' for x in range(11)]
  File "<stdin>", line 1
    lst = [if x % 2 == 0 else 'odd' for x in range(11)]
            ^
SyntaxError: invalid syntax

What am I doing wrong?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

4 Answers4

7

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Is this what you wanted?

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

If that is the case you where simply missing something to return in the list comprehension, in this case you want to return x if the condition is satisfied.

yatu
  • 86,083
  • 12
  • 84
  • 139
1
lst = [x if x % 2 == 0 else 'odd' for x in range(11)]

for more details regarding list comprehension and ternary operator, here the links: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions https://docs.python.org/3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

Julien Briand
  • 275
  • 1
  • 7
1

You're missing the value that should be shown if the if statement is true

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

should be

[x if x % 2 == 0 else 'odd' for x in range(11)]
Sayse
  • 42,633
  • 14
  • 77
  • 146