python sys.getsizeof method returns different size of same kind of lists

痞子三分冷 提交于 2021-02-11 07:38:14

问题


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


回答1:


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.




回答2:


Python knows how long list a will be, so it makes it exactly that long.

Python doesn't know exactly how long list b will be, because map() is lazy, so the list must grow as items are added to it. Memory allocation is relatively time-consuming, so when it needs more space, Python adds room for more items than you're adding to avoid having to allocate memory each time. This means there are often empty slots in dynamically-generated lists.

If those 24 bytes of memory are really important to you, you can simply instruct Python to make a copy of b by slicing: b[:]. Since Python knows how long b is, the copy will have exactly that number of slots and take up the least amount of memory possible.

As nosklo notes, this behavior is an implementation detail.



来源:https://stackoverflow.com/questions/52706811/python-sys-getsizeof-method-returns-different-size-of-same-kind-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!