为什么在删除元素后,Python中列表的容量从8减少到了10?

为什么在删除元素后,Python中列表的容量从8减少到了10?,python,list,size,dynamic-memory-allocation,python-internals,Python,List,Size,Dynamic Memory Allocation,Python Internals,为什么容量从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 ca

为什么容量从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,空间不是1

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

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

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

容量恰好是10,因为
删除
-将元素减少到容量的一半以下会导致收缩,而且(目前)调整大小例程会将超额分配计算为

new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
new\u allocated=(newsize>>3)+(newsize<9?3:6);

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

此计算是什么
(sys.getsizeof(lst)-36)//4)
只是一个旁注,
列表总是比实际元素有更多的空间。这是为了防止在没有空间的情况下频繁复制元素。为什么您希望列表的大小立即缩小?@cᴏʟᴅsᴘᴇᴇᴅ  我已经对我的问题进行了编辑,在这里我回答了这个
sys.getsizeof(lst)-36
nw的计算,为我们为什么要用4除以它提供了更多的上下文,因为36字节是列表数据结构本身在32位上所需的大小。对于单个元素,为一个指针分配了空间,因此额外增加了4个字节—总共40个字节。好的,到目前为止。请将此用于更多上下文。我正在寻找一个答案,帮助我理解它是如何缩小的:)这不是文档。这是一个代码注释。它也不是说你认为它是什么;它描述的是增长,而不是收缩,这只是将项目逐个添加到新的空列表中的增长模式。现在我接受你的回答,你能告诉我们,在上面提到的不同实现中,输出是不同的吗?@AshUpadhyay:这真的是一种错误的思维。也就是说,我对任何其他Python实现代码库都不太熟悉,无法向您指出它们的调整大小策略实现,但是如果您试图测量PyPy 2.6.0上列表的大小,如果您认为这是一种错误的思维方式,我对此表示歉意。正如我向你提到的那样,我已经接受了你的回答。我只是问,既然你这么说了,你真的检查过它的不同实现了吗。因为无论我问什么我都有正当的理由。我不是有意冒犯你。不管怎么说,我得到了我的答案,我真的非常感谢你的真诚回答,否则我不会这么想的。