Why do I get this result at the REPL?
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
My understanding is that is only evaluates to True if the two variables point to the same object, when in this case they’re different objects with the same value. == would evaluate to True, but is shouldn’t.
Going further:
>>> b.reverse()
>>> (a, b)
([3, 2, 1], [3, 2, 1])
It seems that as far as the interpreter is concerned, they are the same object, and operations on b will automatically be performed on a. Again, why?
When you do
a = [1, 2, 3]you’re binding the nameato a list object. When you dob = a, you’re binding the namebto whateverais – in this case the list object. Ergo, they’re the same… An object can have multiple names. It’s worth reading up on the Python Data Model.If you wanted to make a copy of your listobj, then you can look at
b = a[:]to use slice to create a shallow copy, orcopy.copyfor a shallow copy (should work on arbitary objects), orcopy.deepcopyfor strangely – a deep copy.You’ll also notice something surprising in CPython which caches short strings/small integers…