1

I'm trying to understand how the memory allocation works in Python. I've taken two lists here, I'm assigning one element to both in different ways. Assignment is done using:

  1. Using the assignment operator in list1
  2. Using the append method in list2

Before assignment both lists occupy the exact same memory, but memory allocation differs after the assignment is done in different ways. Look at the code below:

from sys import getsizeof as size

list1 = []
list2 = []

print(f"Memory reserved by list1 before assignment: {size(list1)}")
print(f"Memory reserved by list2 before assignment: {size(list2)}")

list1 = [8]
list2.append(8)

print(f"Memory reserved by list1 after assignment: {size(list1)}")
print(f"Memory reserved by list2 after assignment: {size(list2)}")

Output:

Memory reserved by list1 before assignment: 56
Memory reserved by list2 before assignment: 56
Memory reserved by list1 after assignment: 64
Memory reserved by list2 after assignment: 88

Both lists have only one element, still the memory allocation differs based on the assignment. How?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • `list1` creates a new list, whereas `list2` is the original list which has been appended and therefore the append "costs more" to create.... – D.L Aug 07 '23 at 18:48
  • Note that `list1 = [8]` does not change the original `list1` in any way, it just creates a new one and discards the original. But this is not the explanation for why they are different in size at the end. – mkrieger1 Aug 08 '23 at 09:19
  • Does this answer your question? [Size of a Python list in memory](https://stackoverflow.com/questions/7247298/size-of-a-python-list-in-memory) – mkrieger1 Aug 08 '23 at 09:22
  • Thanks @mkrieger1. Yes this answer is very helpful. – user22352079 Aug 29 '23 at 10:44

0 Answers0