Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
列表名称的id在python中指定了什么?_Python_List - Fatal编程技术网

列表名称的id在python中指定了什么?

列表名称的id在python中指定了什么?,python,list,Python,List,我编写了一个代码来打印名称的id,以及列表的元素: 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

我编写了一个代码来打印名称的
id
,以及
列表的元素

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
列表
中的第一个元素不同于
C
中的
数组


如果没有,请告诉我列表名称的
id
/
地址指定了什么,以及
列表的成员如何存储在内存块中?我最近从
C
切换到
python

TLDR:python
列表
不是值数组。它们是指向值的指针数组

id
的确切值是cpython解释器(由python软件基金会开发的python实现)的一个实现细节。根据语言的定义,它只能保证唯一地标识对象

关于cpython:


在python中,所有对象(可以指定给变量的任何对象都是对象)都以结构形式存储在堆中,其中包含有关引用计数、类型、值等的信息。。。
id
函数恰好作为指向该结构的指针的值来实现。python
列表
具有相同的结构,“值”最终是指向其他PyObject结构的指针数组。这些指针与指针数组的位置没有关系(引用计数是另一个讨论),因此不希望它们以任何顺序出现。甚至像整数这样简单的东西也必须有一个PyObject结构。

与C不同,在python
list
对象中,它们包含的东西是独立分配的。列表中的对象可以位于内存中的任何位置(不一定是连续的)。列表对象本身有一些与其相关联的内存,这些内存也可能位于内存中的任何位置(不受内容存储位置的限制)。列表本身具有对它应该存储的对象的引用。在C语言中,这就像一个指针数组(过于简单化)。同样值得注意的是,
id()
函数应该只返回“对象的唯一标识符”。-它返回内存位置的事实是一个CPython实现细节&而不是python语言规范的一部分。
id
是在创建对象时分配给它的。
id
是对象的内存地址,每次运行程序时都会有所不同。(除了某些具有常量唯一id的对象,如-5到256之间的整数)