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:
- Using the assignment operator in
list1 - Using the
appendmethod inlist2
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?