Just think of python variables as labels to objects, not as storing stuff or even references to something.
In fact you don't event need copy module... since when you slice a list it returns a new list object with the objects needed, you can use a slice to give a new list with all objects, a copy:
>>> a = [1, 2, 3]
>>> b = [a[:], a[:], a[:]]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b[1][1]
2
>>> b[1][1] = 4
>>> b
[[1, 2, 3], [1, 4, 3], [1, 2, 3]]
You get changed only the 2nd list, because you created three copies:
>>> a is a
True
>>> a[:] is a[:]
False
>>> a[:] == a[:]
True
The same happen for elementary types, they are no exception, but the behavior with them may be different because they are immutable and may be the same object. With integers, for instance, in this case, with small integers,
>>> x = 10
>>> y = x - 1
>>> z = x - 1
>>> y == z
True
>>> y is z
True
Both y and z are integers with the same value and are the same object. But with large integers, the same may not happen:
>>> x = 123456789
>>> y = x - 1
>>> z = x - 1
>>> y == z
True
>>> y is z
False
Here they have the same value, but they are not the same object. Since they are immutable, it doesn't matter, just to keep in mind to always think if you want to make comparisons by value (==) or by identity (is)
"==" compare by value, if both objects have the same value, while "is" compare by identity, if they are the same object.
Example, here x and y have the same value, but are not the same objects.
>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y
False
Here x and y are the same object, and therefore have the same value:
>>> x = y = [1, 2, 3]
>>> x == y
True
>>> x is y
True
But, when you deal with immutable objects, Python have an internal cache, so they may be the same object, but you have no guarantee, so be careful if you want to check by value or identity...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment