python程序保存在哪里,Python列表在哪里保存其值?

本文探讨了Python中列表对象的内存管理机制。列表实际上是一个存储长度和元素内存位置的数组,而非直接存储值。当列表填充到一定容量时,其内存会按比例增长,以提高插入和追加操作的效率。通过`sys.getsizeof()`可以观察到这种内存分配的变化。然而,不同于类实例的`__dict__`属性,列表没有类似的内部结构来存储其元素的引用。
摘要由CSDN通过智能技术生成

From introspection perspective, where list values are located in the class object.

If list object is class in python:

>>> a = ['one', 'two']

>>> type(a)

So it is stored somewhere in the class, but where?

For example:

If we define a class with values:

class Test:

def __init__(self):

self.test_name = "Do Not"

self.test_surname = "Know"

It is easy to locate an instance values:

>>> b = Test()

>>> print(a.__dict__)

{'test_surname': 'Know', 'test_name': 'Do not'}

Is there similar option to reach those values in the list class object?

解决方案

This is really up to the implementation detail. In cpython, the container object only hold references (pointers) to the stored values. Any operation involving the list internals only manipulates the pointers, not the objects.

Memory is over-allocated so that there are always some free slots available, which makes appends and inserts faster. The space allocated increased by about 12.5% when full. You can actually see that yourself by appending to a list and calling sys.getsizeof in a loop:

>>> import sys

>>> l = []

>>> for i in range(100):

... print(sys.getsizeof(l)),

... l.append(None)

...

72 104 104 104 104 136 136 136 136 200 200 200 200 200 200 200 200 272 272 272 272 272 272 272 272 272 352 352 352 352 352 352 352 352 352 352 440 440 440 440 440 440 440 440 440 440 440 536 536 536 536 536 536 536 536 536 536 536 536 648 648 648 648 648 648 648 648 648 648 648 648 648 648 776 776 776 776 776 776 776 776 776 776 776 776 776 776 776 776 920 920 920 920 920 920 920 920 920 920 920

You can not find a dict of the items behind the scenes somewhere, like you have done with the attributes. The list itself is merely an array storing it's length and the memory locations of the items.

KM4No.png

image source: here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值