Python"sys.getsizeof"从列表/字典中删除项目后报告相同的大小? [英] Python "sys.getsizeof" reports same size after items removed from list/dict?

查看:94
本文介绍了Python"sys.getsizeof"从列表/字典中删除项目后报告相同的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当使用sys.getsizeof()检查列表和字典的大小时,会发生一些有趣的事情.

I notice that when using sys.getsizeof() to check the size of list and dictionary, something interesting happens.

我有:

a = [1,2,3,4,5]

大小为56字节(空列表的大小为36,因此很有意义,因为20/5 = 4)

with the size of 56 bytes (and empty list has size of 36, so it makes sense because 20/5 = 4)

但是,当我删除列表中的所有项目(使用.remove或del)后,大小仍然为56.这对我来说很奇怪.大小不应该回到36吗?

however, after I remove all the items in the list (using .remove or del), the size is still 56. This is strange to me. Shouldn't the size be back to 36?

有什么解释吗?

推荐答案

删除元素时,该列表不承诺释放内存.列表被过度分配,这就是它们如何具有附加元素的摊销O(1)性能.

The list doesn't promise to release memory when you remove elements. Lists are over-allocated, which is how they can have amortized O(1) performance for appending elements.

数据结构时间性能的详细信息: http://wiki.python.org/moin/TimeComplexity

Details of the time performance of the data structures: http://wiki.python.org/moin/TimeComplexity

这篇关于Python"sys.getsizeof"从列表/字典中删除项目后报告相同的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆