我定义了如下两个列表:
import sys
lst = list(range(1, 10, 1))
llst = ([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(sys.getsizeof(llst), sys.getsizeof(lst))
这是我看到的输出:152 128
为什么这两个列表的大小不同,而它们似乎具有相同数量的元素?
我在Windows 11上使用Python 3.10.5。
我定义了如下两个列表:
import sys
lst = list(range(1, 10, 1))
llst = ([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(sys.getsizeof(llst), sys.getsizeof(lst))
这是我看到的输出:152 128
为什么这两个列表的大小不同,而它们似乎具有相同数量的元素?
我在Windows 11上使用Python 3.10.5。
1条答案
按热度按时间2izufjch1#
差异来自“超额分配”,来自源代码:
但确切的行为是实现细节!
在Python 3.10中:
在Python 3.5.1中:
我很确定当
.append()
被调用时会发生这种情况(列表理解也是如此),这就是为什么在两个版本中,lst2
和lst4
都有最大的大小。看起来像是在Python 3.10中,对于
lst1
,解释器从range
对象说OK,我知道(__len__
and__length_hint__
)它需要10个元素,所以我构建了一个10个元素的列表,不需要过度分配。