Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Trueon the first one but the opposite when I change either of A or B's value?

like image 461
Burak. Avatar asked Apr 01 '26 21:04

Burak.


1 Answers

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

like image 142
B. Eckles Avatar answered Apr 04 '26 09:04

B. Eckles



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!