I always thought x += 1
was just syntactic shorthand (and exactly equivalent to) x = x + 1
, until I spent a while trying to figure out why this code wasn't acting as intended:
[ipython/euler 72 ]$ def func(mylist):
mylist += random.sample(range(100),2)
# do stuff with the random result, then restore original list
mylist = mylist[:-2]
It's supposed to return the same list it gets, but it doesn't seem to work that way:
[ipython/euler 81 ]$ x = [1,2,3]
[ipython/euler 82 ]$ func(x)
[1, 2, 3, 23, 7]
[ipython/euler 83 ]$ func(x)
[1, 2, 3, 23, 7, 42, 36]
[ipython/euler 84 ]$ func(x)
[1, 2, 3, 23, 7, 42, 36, 0, 5]
If I change the assignment statement to the long form mylist = mylist + ...
, it works as expected and leaves the list unchanged.
Why is this happening? I assume it has to do with lists being mutable and possibly iadd not being 'real' addition when called as an overloaded method of list, but I still expected the interpreter to see them as equivalent.