Reputation: 598
I'm total beginner to Python, so please could you explain me why the following situation happens. Consider the following code:
>>> A = [1, 2, 3, 4]
>>> B = A[0:2]
>>> print id(A) == id(B)
False
>>> print id(A[0]) == id(B[0])
True #Why?
>>> A[0] = 9
>>> A
[9, 2, 3, 4]
>>> B
[1, 2]
>>> print id(A[0]) == id(B[0])
False #Contradiction?
As you can see from the code above, I slice the list A and copy it to B, but, why print id(A[0]) == id(B[0])
evalutes True
on the first one but the opposite when I change either of A or B's value?
Upvotes: 3
Views: 145
Reputation: 107337
Basically, python doesn't create new objects from every item within a list, whenever you copy/slice a it.
But, Although this won't cause any trouble with immutable objects, you should be careful with mutable objects:
In [22]: A = [[1, 2], 2, 3, 4]
In [23]: B = A[0:2]
In [24]: id(A[0]) == id(B[0])
Out[24]: True
In [27]: A[0][1] = 99
In [28]: B
Out[28]: [[1, 99], 2]
In this case you can use copy.deepcopy
to create a new object of the slice:
In [32]: import copy
In [33]: B = copy.deepcopy(A[0:2])
In [34]: A[0][1] = 5
In [35]: B
Out[35]: [[1, 99], 2]
In [36]: id(A[0]) == id(B[0])
Out[36]: False
^
New Object
Upvotes: 1
Reputation: 1644
When you do B = A[0:2]
, that ends up essentially doing this, as part of it: B[0] = A[0]
. So the object (the integer 1
) in A[0]
is the same object which is in B[0]
.
When you set A[0] = 9
, then those objects are no long the same.
Also, as @ŁukaszRogalski pointed out CPython caches small integers. So we've got A[0] == 1 == B[0]
, and id(1) == id(1)
.
When A[0] == 9
, then 9 != 1 == B[0]
, and id(9) != id(1)
.
Upvotes: 2
Reputation: 1916
Try this:
id(1) == id(1) #True
The reason is that these number constants will be reused throughout the program. So its like some memory is given to store 1 and then wherever 1 is mentioned in the program, the same memory will be used so only a reference to that memory will be created. Object remains the same.
Upvotes: 2