显然,删除字典中的条目不会触发任何大小调整。只有在添加条目后才会触发调整大小。
这可以从以下方面看出:
# Drastic example, nobody does such
# things with dicts FWIK
from sys import getsizeof
d = {i:i for i in range(100)}
print(getsizeof(d)) # 4704
for i in range(100):
del d[i] # similarly with pop
print(getsizeof(d)) # 4704
d[0] = 1 # triggers resize
a question on SO
(根据我的发现)。
set
s的行为方式类似,这与dicts的行为一致。
list
list_resize
comment
:
/* Bypass realloc() when a previous overallocation is large enough
to accommodate the newsize. If the newsize falls lower than half
the allocated size, then proceed with the realloc() to shrink the list.
*/
为什么字典(以及间接的集合)不采用类似的技巧,而是等待插入新条目?所描述的行为适用于Python 2.7和3.x(直到Python 3.7.0a0)。