简体   繁体   English

在 python 的 for 循环中列出 append 的可变性

[英]List mutability with append in for loop in python

I'm new to the concept of mutability of lists in the context of for loops.我对 for 循环上下文中列表可变性的概念不熟悉。

Can someone explain why the output for the below code is an empty list?有人可以解释为什么下面代码的 output 是一个空列表吗?

I would expect L3 = [3,4] .我希望L3 = [3,4]

Thanks!谢谢!

L1 = [1,2,3,4]
L2 = [1,2,5,6]

def no_dups(L1, L2):
    L3 = []
    for e in L1:
        if e not in L2:
            L3.append(e)
    return(L3)

print(L3)

The last line print(L3) does not even call no_dups function.最后一行print(L3)甚至没有调用no_dups function。 It throws an expection because L3 is not defined outside of function.它引发了一个期望,因为 L3 没有在 function 之外定义。

Probably you meant this:可能你的意思是这样的:

L3 = no_dups(L1, L2)
print(L3)

In which case you do inded get the expected result.在这种情况下,您确实会得到预期的结果。

This works:这有效:

>>> L1 = [1,2,3,4]
>>> L2 = [1,2,5,6]
>>> 
>>> def no_dups(L1, L2):
...     L3 = []
...     for e in L1:
...         if e not in L2:
...             L3.append(e)
...     return(L3)
... 
>>> print(no_dups(L1,L2))
[3, 4]
>>> 

L3 does not actually exists outside of no_dups() , so you cannot print it or whatever L3实际上并不存在于no_dups()之外,因此您无法打印它或其他任何东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM