提问人:Neeraj-Kumar-Coder 提问时间:2/26/2021 更新时间:2/26/2021 访问量:3824
python中列表名称的id指定了什么?
What does the id of the name of the list specify in python?
问:
我写了一个代码来打印名称和元素:id
list
sample_list = [1, 2, 3, 4, 5]
print(f"The id of the name of the list is = {id(sample_list)}")
for i in range(0, len(sample_list)):
print(f"Id of element index {i} is {id(sample_list[i])}")
输出:
The id of the name of the list is = 2874211984576
Id of element index 0 is 2874206087472
Id of element index 1 is 2874206087504
Id of element index 2 is 2874206087536
Id of element index 3 is 2874206087568
Id of element index 4 is 2874206087600
我想知道为什么名称与它的第一个元素不同?id
list
list
C
arrays
如果没有,请告诉我列表名称的 / 指定了什么以及 的成员如何存储在内存块中?我最近从 .id
address
list
python
C
答:
3赞
Aaron
2/26/2021
#1
TLDR:python 不是值数组。它们是指向值的指针数组。list
的确切值是 cpython 解释器(由 python 软件基金会开发的 python 实现)的实现细节。根据语言的定义,它只能保证唯一标识对象。id
关于 cpython:
在 python 中,所有对象(您可以分配给变量的任何对象都是对象)都作为结构存储在堆中,其中包含有关引用计数、类型、值等的一些信息......该函数恰好被实现为指向该结构的指针的值。python 具有相同的结构,并且“值”最终是指向其他 PyObject 结构的指针数组。这些指针与指针数组的位置无关(引用计数是另一个讨论),因此不希望它们按任何顺序排列。即使是像整数这样简单的东西也必须具有这些 PyObject 结构之一。id
list
评论
list
id()
id
id