List item keeps same memory address following sort/copy

156 views Asked by At

Ive recently become confused about how lists work internally. This code tracks the memory address of the item '1' in these lists following some operations:

a = [1, 0, 2]
b = sorted(a)
c = b[:]

print id(a[0])  
print id(b[1])  # Same memory address
print id(c[1])  # Same memory address

The address stays the same in the three lists. How do all the lists contain the same item '1'?

4

There are 4 answers

2
tynn On BEST ANSWER

Internally (CPython) the list object stores references to the Python objects it contains. Therefore adding the contents of one list to another won't create new objects. It'll only increment the reference count.

4
Łukasz Rogalski On

Python caches small integers internally (up to 256).

a = 1
b = 1
assert a is b

c = 257
d = 257
assert c is d  # raises AssertionError
2
NDevox On

To add on top of @LukaszR. answer.

While small integers share the same id, copied lists do not.

So:

>>> a = [1,2,3]
>>> b = a[:]
>>> c = a
>>> id(a[0]) == id(b[0])
True
>>> id(a) == id(b)
False
>>> id(c) == id(a)
True
0
Ravi Kumar On
>>> a=5
>>> id(a)
13897976 #newly created object id
>>> b = 5

This time python finds for 5 integer object, if it finds 5 just it tags another name to 5(above it tags for b).

>>> id(b)
13897976 # existing 5 integer object id

>>> list1= [25, 5, 0, 'python']

Same happens when creating list when you are assigning objects to list, it searches for object in memory if python finds object it just tags list index to that object. if not it will create new memory for that object

>>> list1[1]
5
>>> id(list1[1])
13897976 # existing 5 integer object id
>>> p= 'python'
>>> id(p)
139673134424000
>>> id(list1[3])
139673134424000

Same thing happen for dictionary's functions, and in your code. more information click