如果将Python列表的ID实现为动态数组,为什么在添加操作后python list的ID不会更改? [英] Why is the id of python list not changing after append operation, if it is implemented as dynamic array?

查看:57
本文介绍了如果将Python列表的ID实现为动态数组,为什么在添加操作后python list的ID不会更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果列表是作为动态数组实现的,则为数组创建新空间时,每次分配的大小都被完全占用时,为什么id不变?

If the list is implemented as a dynamic array, every time the allocated size is completely occupied if the new space is created for the array, why is the id not changing?

>>> a=[]

>>> id(a)
4395087184

>>> for i in range(1000):
     a.append(i)


>>> id(a)
4395087184

推荐答案

保证对象的 id 在该对象的生命周期内是持久的.因此,如果此列表的 id 更改,它将违反 id 函数的规范,并且您仅创建了一个列表,因此不会有两个具有不同 id的列表对象 s.

The id of an object is guaranteed to be persistent for the lifetime of the object. So it would violate the specification of the id function if this list's id changed, and you only created one list so there aren't two list objects with different ids.

这在实践中的工作方式是列表对象本身保留在相同的内存位置,但是它持有对后备数组的(私有)引用.当阵列的容量需要更改时,将创建一个新的后备阵列,并复制内容.列表对象的(私有)引用已更新为指向新的后备数组,但列表对象本身尚未在内存中重定位.

The way this works in practice is that the list object itself stays in the same memory location, but it holds a (private) reference to the backing array. When the array's capacity needs to change, a new backing array is created and the contents are copied across. The list object's (private) reference is updated to point at the new backing array, but the list object itself hasn't been relocated in memory.

我写了关于如何进行详细解释这项工作有效,包括一个交互式示例,该示例显示了列表对象和支持数组的箱形图和指针图.您可能会发现这有助于了解调整后备数组大小时内存中实际发生的情况.

I have written a longer explanation of how this works, including an interactive example which shows box-and-pointer diagrams of the list object and the backing array. You may find this helpful to understand what is actually happening in memory when the backing array is resized.

这篇关于如果将Python列表的ID实现为动态数组,为什么在添加操作后python list的ID不会更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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