【问题标题】:Difference between list = [] vs. list.clear()list = [] 与 list.clear() 之间的区别
【发布时间】:2019-04-29 05:21:40
【问题描述】:

list = []list.clear() 有什么区别?

根据我的代码行为和我自己的观察,list.clear() 删除了它的条目以及我用来附加其数据的条目。

例子:

container.append(list)
list.clear()

container 也将是 []

【问题讨论】:

标签: python python-3.x list


【解决方案1】:

调用clear 会从列表中删除所有元素。分配[] 只是将该变量替换为另一个空列表。当您有两个变量指向同一个列表时,这一点变得很明显。

考虑以下 sn-p:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1.clear()
>>> l1 # l1 is obviously empty
[]
>>> l2 # But so is l2, since it's the same object
[]

与这个相比:

>>> l1 = [1, 2, 3]
>>> l2 = l1
>>> l1 = []
>>> l1 # l1 is obviously empty
[]
>>> l2 # But l2 still points to the previous value, and is not affected
[1, 2, 3]

【讨论】:

    【解决方案2】:

    如果您查看生成的字节码,您也可以看到这一点。这里是x = []的部分

    import dis
    
    print("Example with x = []")
    
    s1 = """
    x = [1,2,3]
    x = []
    """
    
    dis.dis(s1)
    

    哪个输出

    Exmaple with x = []
      2           0 LOAD_CONST               0 (1)
                  2 LOAD_CONST               1 (2)
                  4 LOAD_CONST               2 (3)
                  6 BUILD_LIST               3
                  8 STORE_NAME               0 (x)
    
      3          10 BUILD_LIST               0
                 12 STORE_NAME               0 (x)
                 14 LOAD_CONST               3 (None)
                 16 RETURN_VALUE
    

    我们可以看到构建了两个列表,因为我们有两个BUILD_LIST。现在如果我们看看x.clear()

    print("Exmaple with x.clear()")
    
    s2 = """
    x = [1,2,3]
    x.clear()
    """
    
    dis.dis(s2)
    

    我们得到以下输出

    Exmaple with x.clear()
      2           0 LOAD_CONST               0 (1)
                  2 LOAD_CONST               1 (2)
                  4 LOAD_CONST               2 (3)
                  6 BUILD_LIST               3
                  8 STORE_NAME               0 (x)
    
      3          10 LOAD_NAME                0 (x)
                 12 LOAD_ATTR                1 (clear)
                 14 CALL_FUNCTION            0
                 16 POP_TOP
                 18 LOAD_CONST               3 (None)
                 20 RETURN_VALUE
    

    这里只构建一个列表并调用 clear 并使用 LOAD_CONSTNone 与初始值 1,2,3 一样放入堆栈。

    【讨论】:

    • x = [] 会比x.clear() 快得多吗?特别是如果x 有很多元素可以使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 2015-03-09
    • 2015-05-22
    • 2015-07-01
    • 2015-08-23
    • 2019-01-31
    • 2011-05-15
    相关资源
    最近更新 更多