38

Very simple line:

i = 3
a = 2 if i in [1, 3, 6] else a = 7

fails with:

SyntaxError: can't assign to conditional expression

whereas expanded as:

if i in [1, 3, 6]:
    a = 2
else:
    a = 7

works fine.

Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • 1
    Sorry guys, every now and then I forget about the extra `=` and end up baffled as to why the line is not working. – Gabriel Oct 05 '15 at 17:38
  • Not a duplicate, previous question was out pros and cons, this is a common copy paste error. – Danny Varod Oct 19 '20 at 14:51

2 Answers2

81

You are using it wrong. Use it this way:

a = 2 if i in [1, 3, 6] else 7

The general form is:

var = val1 if cond else val2
Aleksandr Kovalev
  • 3,508
  • 4
  • 34
  • 36
11

Should be

 a = 2 if i in [1, 3, 6] else 7

You can read it as:

 a = (((2 if i in [1, 3, 6] else 7)))

which is to say that the expression on the right side of the assignment sign is fully evaluated and the result then assigned to the left side. The expression itself is two values separated by the condition.

Larry Lustig
  • 49,320
  • 14
  • 110
  • 160