I'm observing a discrepancy in Python's behavior when using the +=
and +
operators with lists. Consider the following code snippets:
x = [1, 2]y = xx += [3]y += [4]print(x is y) # Output is True
In this case, the output is True
, indicating that x
and y
reference the same object in memory. However, when I slightly modify the code:
x = [1, 2]y = xx += [3]y = y + [4]print(x is y) # Output is False
The output is False
, suggesting that x
and y
now reference different objects. While +=
is often considered syntactic sugar for list concatenation, this behavior contradicts that understanding.
Could someone clarify the difference in behavior between +=
and +
when used with lists? I'm interested in understanding the underlying mechanisms.