I am making two lists in IDLE of Python 3.7 there names are a and b they are going to differ in terms of initialization but the content is same(as I think so, but maybe I am wrong)
>>>a = [1,2,3,4]
>>>a
[1, 2, 3, 4]
>>>b = list(map(lambda x:x,a))
>>>b
[1, 2, 3, 4]
however when I want to know their size with help of sys.getsizeof method sys.getsizeof(a) returns 96 whereas sys.getsizeof(b) returns 120
so can anyone help me to understand why is this happening? PS: i was just trying out map function
Since your first list a
is defined from a literal, it is created with a size "to fit", while the second one b
is dynamically growing in runtime, enlarged at realtime to fit more elements before python knows there will be elements or not.
That is why you get different sizes.
Lists grow and shrink internally based on a number of factors. It is an implementation detail. As an example, in my CPyhton 3 implementation:
import sys
l = []
for x in range(10):
print(x, sys.getsizeof(l))
l.append(x)
The results:
0 64
1 96
2 96
3 96
4 96
5 128
6 128
7 128
8 128
9 192
As you can see the list is growing in size, but sometimes I get the same size in bytes, until it "grows" only in specific points. This is to save computing power growing once instead of growing on every increase.