为什么 Python 中的 List 去掉元素后容量从 8 个减少到 10 个?

Why does the capacity of List in Python reduced to 10 instead of 8 after removing elements?

为什么容量从 8 个减少到 10 个?

#Do not remove the below import statement
import sys
'''This function provides the capacity, size and space left in the list.
You can invoke it to get the details of the list'''

def list_details(lst):

    #Number of elements that can be stored in the list
    print("Capacity:", (sys.getsizeof(lst)-36)//4)

    #Number of elements in the list
    print("Size:", len(lst))

    #Number of elements that can be accommodated in the space left
    print("Space Left:", ((sys.getsizeof(lst)-36) - len(lst*4))//4)

    #formula changes based on the system architecture
    #(size-36)/4 for 32 bit machines and
    #(size-64)/8 for 64 bit machines
    # 36, 64 - size of an empty list based on machine
    # 4, 8 - size of a single element in the list based on machine

marias_lst=[]
print("Empty list created!!!")
print("List details:")
list_details(marias_lst)
for i in range(0,10):
    marias_lst.append(1)

print("List details After adding 10 elements :")
list_details(marias_lst)
for i in range(0,3):
    marias_lst.remove(1)

print("List details after removing 3 elements:")
list_details(marias_lst)

我正在使用上面的程序来了解 python 中列表的增长是如何发生的。我的疑问是什么时候 我添加 1 个元素,容量增加到 4 我添加 5 个元素,容量增加到 8 我添加10个元素,容量增加到16

现在,当我在添加 10 个元素后删除 3 个元素时,我得到以下输出

Empty list created!!!
List details:
Capacity: 0
Size: 0
Space Left: 0
List details After adding 10 elements :
Capacity: 16
Size: 10
Space Left: 6


List details after removing 3 elements:
Capacity: 10
Size: 7
Space Left: 3

为什么容量不是 8 而 space 剩下 1?

**编辑 1 ** 在 32 位机器 python 解释器上,我们的列表增长如下所示

>>> import sys
>>> sys.getsizeof([])
36
>>> sys.getsizeof([1])
40
>>> lst = []
>>> lst.append(1)
>>> sys.getsizeof(lst)
52

没有理由期望容量为 8。如果您 运行 在新的 Python 版本或不同的实现上,也没有理由期望容量再次为 10 (比如 PyPy)。它恰好是 10 这一事实是您不应依赖的实现细节,也不要期望保持不变。

容量恰好是 10,因为 remove-ing 减少到少于容量一半的元素触发了收缩,并且(目前,on modern CPython)调整大小例程将过度分配计算为

new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);

newsize 为 7 时,这将产生一个 3 元素的过度分配,新容量为 10。