2

I'm just getting started with Python and was reading about list comprehensions.

The following code:

my_list = [x ** x for x in range(1,11) if x % 2 == 0]
print(my_list)

... produces this output:

[4, 256, 46656, 16777216, 10000000000]

I then tried this code:

my_list = [x ** x for x in range(1,11) if x % 2 == 0 else 7]
print(my_list)

... but I got a syntax error starting at the second "e" in else.

Can someone explain why I'm getting a syntax error? I'd like to have the list create a list of even squares based on the value of the base (x), and to have the value "49" if the list value is not an "even number" square.

martineau
  • 119,623
  • 25
  • 170
  • 301
slantalpha
  • 515
  • 1
  • 6
  • 18

1 Answers1

0

In this case, you would want

my_list = [x ** x if x % 2 == 0 else 49 for x in range(1,11)]

If you use an if at the end of a list comprehension like that, it is used to select which elements to include. If you want a different result depending on the case, you need to use a ternary if at the beginning instead.

For more info, take a look at the docs here. To quote:

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

There is no support for else here, presumably because a ternary if (if condition then foo else bar) in the 'body' of the comprehension already accomplishes this and "There should be one-- and preferably only one --obvious way to do it."

Steven Fontanella
  • 764
  • 1
  • 4
  • 16