列表项在排序/复制后保持相同的内存地址 [英] List item keeps same memory address following sort/copy

查看:114
本文介绍了列表项在排序/复制后保持相同的内存地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近对列表在内部的工作方式感到困惑.遵循一些操作,此代码将跟踪这些列表中项目"1"的内存地址:

Ive recently become confused about how lists work internally. This code tracks the memory address of the item '1' in these lists following some operations:

a = [1, 0, 2]
b = sorted(a)
c = b[:]

print id(a[0])  
print id(b[1])  # Same memory address
print id(c[1])  # Same memory address

三个列表中的地址保持不变.所有列表如何包含相同的项目"1"?

The address stays the same in the three lists. How do all the lists contain the same item '1'?

推荐答案

在内部(CPython)列表对象存储对其包含的Python对象的引用.因此,将一个列表的内容添加到另一个列表将不会创建新对象.只会增加引用计数.

Internally (CPython) the list object stores references to the Python objects it contains. Therefore adding the contents of one list to another won't create new objects. It'll only increment the reference count.

这篇关于列表项在排序/复制后保持相同的内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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