乱搞别名
我有以下代码,可以按预期工作:
a = [1, 2, 3, 4]
b = a
>>> b is a
True
如果我稍微改变一下它仍然可以工作:
a = [1, 2, 3, 4]
b = a[2] * 2
>>> b is a[2] * 2
True
现在的问题是:
a = [1, 2, 3, 4]
b = a * 2
>>> b is a * 2
False
有人可以向我解释一下为什么它返回 False,而 b 是 a[2] * 2 返回 True?
I have the following code that works as expected:
a = [1, 2, 3, 4]
b = a
>>> b is a
True
if I change it up a little it still works:
a = [1, 2, 3, 4]
b = a[2] * 2
>>> b is a[2] * 2
True
Now the problem:
a = [1, 2, 3, 4]
b = a * 2
>>> b is a * 2
False
Can someone please explain to me why this returns False, while b is a[2] * 2
returns True?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当
a
是列表时,a * 2
创建一个新的列表实例。如果您调用a * 2
两次,则会创建两个新的列表实例 - 这就是为什么b is a * 2
会产生False
。b is a[2] * 2
得到True
的原因是 CPython 对缓存小整数的优化。由于整数在 Python 中是不可变的,因此实际上获取新实例还是缓存实例并不重要,并且对于小整数,如果再次命中相同的整数,Python 将返回缓存版本。也尝试一下When
a
is a list,a * 2
creates a new list instance. If you calla * 2
twice, you create two new list instances -- that's whyb is a * 2
yieldsFalse
.The reason that you get
True
forb is a[2] * 2
is an optimisation of CPython that caches small integers. Since integers are immutable in Python, it actually does not matter if you get a new instance or a cached one, and for small integers, Python returns a cached version if you hit the same integer again. Also try比较时,相同的列表并不等效,除非它们引用相同的列表。仅仅因为列表具有相同的值并不意味着它们引用内存中的相同列表。
例如,
它们指向不同的内存位置是有道理的,因为如果您可能想说更改第一个列表(例如将
4
附加到末尾a
)而不修改 <如果a
和b
指向内存中的同一位置,则这是不可能的。Identical lists aren't equivalent when compared
is
unless they reference the same list. Just because the lists have the same values doesn't mean they reference the same list in memory.E.g.,
This makes sense that they point to different memory locations, because if you may want to say change the first list (like append
4
to the enda
) without modifyingb
which wouldn't be possible ifa
andb
pointed to the same location in memory.a * 2 构造一个新列表,而整数与其自身具有同一性。
a * 2 constructs a new list, while an integer has identity with itself.