Python "a=a-b" and "a-=b" are really equivalent?

python

Solution

Yes, they are different. Compare the following:

>>> x = set([1,2,3])
>>> y = x
>>> y -= set([1])
>>> x
set([2, 3])

>>> map(id, (x, y))
[18641904, 18641904]

with

>>> x = set([1,2,3])
>>> y = x
>>> y = y - set([1])
>>> x
set([1, 2, 3])

>>> map(id, (x, y))
[2774000, 21166000]

In other words, `y -= set(...)` changes `y` in place. Since both `x` and `y` refer to the same object, they both change.

On the other hand, `y = y - set(...)` creates a new object, rebinding `y` to refer to this new object. `x` is unaffected since it still points to the old object.

Problem

It seems that `a = a-b` differs from `a -= b` and I don't know why. Code: ``` cache = {} def part(word): if word in cache: return cache[word] else: uniq = set(word) cache[word] = uniq return uniq w1 = "dummy" w2 = "funny" # works test = part(w1) print(test) test = test-part(w2) print(test) print(cache) # dont't works test = part(w1) print(test) test -= part(w2) # why it touches "cache"? print(test) print(cache) ``` Result: ``` set(['y', 'm', 'u', 'd']) set(['m', 'd']) {'dummy': set(['y', 'm', 'u', 'd']), 'funny': set(['y', 'n', 'u', 'f'])} set(['y', 'm', 'u', 'd']) set(['d', 'm']) {'dummy': set(['d', 'm']), 'funny': set(['y', 'n', 'u', 'f'])} ``` As you can see, the third and the last line differs. Why in the second case the variable "cache" is different? `test -= part(w2)` is not like `test = test-part(w2)`? Edit 1 - Thanks for the answers, but why the var `cache` changes?

Original source