Why aren't these two ternary expressions equal?

94 Views Asked by At

When I run the below code, I get two different values for i. Why?

The only difference is the first uses i = i + 1 whereas the second uses i += 1 which are equivalent in all other use cases I've seen.

i = 1
k = 2
i = i + 1 if i == k else k
print(i) # prints 2

i = 1
k = 2
i += 1 if i == k else k

print(i) # prints 3

1

There are 1 best solutions below

0
On

According to Python's operator precedence rules, in the first example the ternary expression applies to i + 1. So the following

i = i + 1 if i == k else k

is equivalent to

i = ((i + 1) if i == k else k)

Whereas the following

i += 1 if i == k else k

is equivalent to

i += (1 if i == k else k)