Is there a difference between the two?
本问题已经有最佳答案,请猛点这里访问。
代码A:
1 2 3  | lst = [1, 2, 3] for i in range(10): lst+= ["42"]  | 
代码B:
ZZU1
我知道输出是一样的,但两个列表的方式有差异吗?后面到底发生了什么事?What's happening in the back actually?
当你这样做的时候
1  | lst += ["42"]  | 
你正在变异
1  | lst = lst + ["42"]  | 
您正在使用
1 2 3 4 5 6  | lst = ["1"] print(id(lst)) lst += ["2"] print(id(lst)) lst = lst + ["3"] print(id(lst))  | 
前两个ID相同,但最后一个ID不同。因为,创建了一个新列表,
如果不知道这两者之间的区别,那么当您将列表作为参数传递给函数并在函数内部附加一个项时,就会产生一个问题。
1 2 3 4 5  | def mutate(myList): myList = myList + ["2"] # WRONG way of doing the mutation tList = ["1"] mutate(tList) print(tList)  | 
你仍然可以得到
1 2 3 4 5  | def mutate(myList): myList += ["2"] # Or using append function tList = ["1"] mutate(tList) print(tList)  | 
将打印