Why does creating a list from a list make it larger?

后端 未结 2 734
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 00:49

I\'m seeing some inconsistencies when using sys.getsizeof on what should be identical lists. (Python 2.7.5)

>>> lst = [0,1,2,3,4,5,6,7,         


        
2条回答
  •  难免孤独
    2020-12-03 01:20

    When you create a list literal, the size reported is the minimum size needed to hold the data. You can see this because the size jumps up if you append a single element. However, when you use list to copy it, it allocates some extra space - it takes a few appends before it reallocates (in your case, I suspect the 8th append will do it - it needs 4 more bytes per element). There is probably a reason why these allocation behaviors are different, but I'm not sure what that might be.

提交回复
热议问题