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'?
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.