有个疑惑

2017-01-21 11:21:45 +08:00
 bxb100
python 中 id([1]) == id([2]) 为 True,这是为啥啊
2880 次点击
所在节点    Python
7 条回复
czheo
2017-01-21 11:28:23 +08:00
性能优化,内部把 list 重用了吧。
imn1
2017-01-21 11:31:24 +08:00
id([1]) is id([2])
bxb100
2017-01-21 11:43:59 +08:00
@czheo tuple 为啥不会出现这种情况
czheo
2017-01-21 11:46:26 +08:00
tuple 是 immutable 的,没法重用
bxb100
2017-01-21 11:52:53 +08:00
@czheo id(()) == id(())返回的为 True
bxb100
2017-01-21 13:32:19 +08:00
@czheo list 是临时对象,内存会自动清理, tuple 不会,而且 ()和(1)存放地址区域不同
HypoChen
2017-01-21 19:20:03 +08:00
id(object)

Return the “ identity ” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. **Two objects with non-overlapping lifetimes may have the same id() value.**

```
>>> id([1])
4391579520
>>> id([2])
4391579520
>>> a = [1]
>>> b = [1]
>>> id([1])
4391757944
>>> id([2])
4391757944
>>> id(a)
4391579520
>>> id(b)
4391641672
>>> id([])
4391757944
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/336021

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX