Burak. Burak. - 1 month ago 15
Python Question

Python slice shows same id location

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?

Answer

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).

Comments