Skip to content Skip to sidebar Skip to footer

List Item Keeps Same Memory Address Following Sort/copy

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

Solution 1:

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

Solution 2:

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.

Solution 3:

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

Solution 4:

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

Post a Comment for "List Item Keeps Same Memory Address Following Sort/copy"