I know the conditional expression in Python is X if C else Y, but I got some problems in using it.
I have two codes to be compared.
Code 1:
def fun(p):
if len(p) >= 2:
p[1] = 'Ok'
else:
p.append('Ok')
p = [1]
fun(p)
print p
Output of code 1:
[1, 'Ok']
Code 2:
def fun(p):
(p[1] = 'Ok') if (len(p) >= 2) else p.append('OK')
p = [1]
fun(p)
print p
Output of code 2:
(p[1] = 'Ok') if (len(p) >= 2) else p.append('OK')
^
SyntaxError: invalid syntax
I know in code 1, whose format is "if C : X else: Y", the evaluation order is:
- C
- X
- Y
Code 2 throws a syntax error, the reason may be p[1] doesn't exist. So I guess the format "X if C else Y" is evaluated as follows:
- X
- C
- Y
But that is only my guess. does anyone know the real reason why code 2 is wrong while code 1 is right?