Python何时为空列表创建新的列表对象? [英] When does Python create new list objects for empty lists?

查看:111
本文介绍了Python何时为空列表创建新的列表对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下对我来说很有意义:

The following makes sense to me:

>>> [] is []
False

鉴于列表是可变的,我希望[]每当出现在表达式中时都是一个新的空列表对象.但是,使用这种解释,以下内容使我感到惊讶:

Given that lists are mutable, I would expect [] to be a new empty list object every time it appears in an expression. Using this explanation however, the following surprises me:

id([]) == id([])
True

为什么?有什么解释?

推荐答案

在第一个示例中,[]并不是[]准确地,因为列表是可变的.如果不是这样,他们可以安全地映射到同一个对象.

In the first example, [] is not [] precisely because the lists are mutable. If they weren't, they could safely map to the same one without issue.

在第二个示例中,id([])创建一个列表,获取ID,然后取消分配该列表.第二次它再次创建一个列表 ,但是将其放在同一位置"是因为没有发生太多其他事情了. id仅在对象的生命周期内有效,在这种情况下,其生命周期实际上为nil

In the second example, id([]) creates a list, gets the id, and deallocates the list. The second time around it creates a list again, but "puts it in the same place" because nothing much else has happened. id is only valid during an object's lifetime, and in this case its lifetime is virtually nil

有关id的文档:

这是一个整数(或长整数),在该对象的生存期内,此整数保证是唯一且恒定的.具有不重叠生存期的两个对象可能具有相同的id()值.

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.


注释拆卸:


Commented disassembly:

   0 LOAD_GLOBAL              0 (id)    # load the id function
   3 BUILD_LIST               0         # create the first list
   6 CALL_FUNCTION            1         # get the id
   9 LOAD_GLOBAL              0 (id)    # load the id function
  12 BUILD_LIST               0         # create the second list
  15 CALL_FUNCTION            1         # get the id
  18 COMPARE_OP               2 (==)    # compare the two ids
  21 RETURN_VALUE                       # return the comparison

请注意,没有STORE_FAST可以保留列表.因此,将其传递给id函数后立即将其丢弃.

Note there is no STORE_FAST to retain the list. Therefore it was discarded immediately after getting passed to the id function.

这篇关于Python何时为空列表创建新的列表对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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