【发布时间】:2017-03-30 14:04:02
【问题描述】:
今天自己在Python 2.7.13中运行了下面给出的代码,发现列表为空时大小不为0:
import sys
data = []
for k in range(n):
a = len(data)
b = sys.getsizeof(data)
print('Length:{0:3d};Size in bytes:{1:4d}'.format(a,b))
data.append(None)
我的机器上的输出:
Length: 0; Size in bytes : 72
Length: 1; Size in bytes : 104
Length: 2; Size in bytes : 104
Length: 3; Size in bytes : 104
Length: 4; Size in bytes : 104
Length: 5; Size in bytes : 136
Length: 6; Size in bytes : 136
Length: 7; Size in bytes : 136
Length: 8; Size in bytes : 136
Length: 9; Size in bytes : 200
Length: 10; Size in bytes : 200
Length: 11; Size in bytes : 200
Length: 12; Size in bytes : 200
Length: 13; Size in bytes : 200
Length: 14; Size in bytes : 200
Length: 15; Size in bytes : 200
Length: 16; Size in bytes : 200
Length: 17; Size in bytes : 272
Length: 18; Size in bytes : 272
Length: 19; Size in bytes : 272
我想知道为什么会这样?
似乎 Python 正在为某些东西保留内存。 那是什么东西??
【问题讨论】:
-
另一个原因是出于效率原因(阅读动态数组和摊销分析en.wikipedia.org/wiki/Amortized_analysis)
-
感谢您的参考..
标签: python python-2.7 list python-3.x python-internals