Python — List elements in Memory

Felix Stephen
3 min readNov 20, 2018

I was going through a couple of deep dive in python list and how the memory is managed, the one made me really confused!

Here is the first example,

~$ python
>>> a = [1, 2, 3, 1, 1, 1]
>>> print(id(a)) # 49375592
>>> print(id(a[0])) # 44792032
>>> print(id(a[1])) # 44792020
>>> print(id(a[2])) # 44792008
>>> print(id(a[3])) # 44792032
>>> print(id(a[4])) # 44792032
>>> print(id(a[5])) # 44792032

As per my understanding variable (a) reference the memory location of list elements that stored. Element 1 is repeated 3 times and it’s pointing to the same memory location, index 1 and 2 pointing different memory location because it’s different elements.

  • What if I remove the element 1 from the list?
  • Will, it removes all the occurrences from the list?
  • Will list.remove(x) is handling index also internally?
>>> a.remove(1) # [2, 3, 1, 1, 1]

Since all the elements(1) are pointing to the same memory location, but it’s removed the first index element, not the other elements. As per the python docs, list.remove(x) will remove the first element that occurs from the list. But still, other occurred elements are pointing to the same memory location.

Here is the second example,

~$ python
>>> b = [[]] * 3 # [[], [], []]
>>> print(id(b)) # 49436632
>>> print(id(b[0])) # 49436712
>>> print(id(b[1])) # 49436712
>>> print(id(b[2])) # 49436712
>>> b[0].append(1) # [[1], [1], [1]]

b is the list which has the three empty lists, are pointing to the same memory location, Here we are appending element 1 to the first indexed list, but it’s appending all other empty lists also because all the list are pointing to the same memory location. In this case, it’s not handling based on the index.

  • How Python has managed memory in terms of remove and append based on the given examples?

Here is the third example,

~$ python
>>> c = [[], [], []]
>>> print(c) # [[], [], []]
>>> print(id(c[0])) # 49376832
>>> print(id(c[1])) # 49376752
>>> print(id(c[2])) # 49376112

In the third example, instead of multiplying empty list, I just added into manually, when I try to check the memory location of each empty list, it’s pointing to the different memory location, not the same memory location.

From the second example, Is it really multiplying memory location also?

How this is different from the [[]] * 3 and [[], [], []]?

Thanks for reading… check out my another blog, Python — Secure Coding Guidelines.

--

--

Felix Stephen

“It’s still Magic even if you know how it’s done.”