Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 272
Francesco Frassinelli Avatar asked Sep 08 '26 13:09

Francesco Frassinelli


1 Answers

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.

like image 80
NPE Avatar answered Sep 11 '26 03:09

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!