这两者之间有区别吗?(复制)

时间:2021-01-09 21:33:07

This question already has an answer here:

这个问题已经有了答案:

code A:

代码:

lst = [1, 2, 3]
for i in range(10):
    lst+= ["42"]

code B:

代码2:

lst = [1, 2, 3]
for i in range(10):
    lst = lst + ["42"]

I know the output is the same, but is there a difference in the way the two lists are built? What's happening in the back actually?

我知道输出是一样的,但是这两个列表的构建方式有区别吗?后面发生了什么?

1 个解决方案

#1


5  

When you do

当你做

lst += ["42"]

You are mutating lst and appending "42" at the end of it. But when you say,

你正在改变lst,并在末尾加上“42”。但是,当你说,

lst = lst + ["42"]

You are creating a new list with lst and "42" and assigning the reference of the new list to lst. Try this program to understand this better.

您正在创建一个包含lst和“42”的新列表,并将新列表的引用分配给lst。尝试这个程序来更好地理解这一点。

lst = ["1"]
print(id(lst))
lst += ["2"]
print(id(lst))
lst = lst + ["3"]
print(id(lst))

The first two ids will be the same, bu the last one will be different. Because, a new list is created and lst now points to that new list.

前两个id是一样的,最后一个id是不同的。因为,创建了一个新列表,lst现在指向这个新列表。

Not knowing the difference between these two will create a problem, when you pass a list as a parameter to a function and appending an item to it, inside the function like this

当您将列表作为参数传递给一个函数并将一个项附加到它时,不知道这两者之间的区别将会产生一个问题

def mutate(myList):
    myList = myList + ["2"] # WRONG way of doing the mutation
tList = ["1"]
mutate(tList)
print(tList)

you will still get ['1'], but if you really want to mutate myList, you could have done like this

你仍然会得到['1'],但是如果你真的想要改变myList,你可以这样做

def mutate(myList):
    myList += ["2"] # Or using append function
tList = ["1"]
mutate(tList)
print(tList)

will print ['1', '2']

将打印(' 1 ',' 2 ')

#1


5  

When you do

当你做

lst += ["42"]

You are mutating lst and appending "42" at the end of it. But when you say,

你正在改变lst,并在末尾加上“42”。但是,当你说,

lst = lst + ["42"]

You are creating a new list with lst and "42" and assigning the reference of the new list to lst. Try this program to understand this better.

您正在创建一个包含lst和“42”的新列表,并将新列表的引用分配给lst。尝试这个程序来更好地理解这一点。

lst = ["1"]
print(id(lst))
lst += ["2"]
print(id(lst))
lst = lst + ["3"]
print(id(lst))

The first two ids will be the same, bu the last one will be different. Because, a new list is created and lst now points to that new list.

前两个id是一样的,最后一个id是不同的。因为,创建了一个新列表,lst现在指向这个新列表。

Not knowing the difference between these two will create a problem, when you pass a list as a parameter to a function and appending an item to it, inside the function like this

当您将列表作为参数传递给一个函数并将一个项附加到它时,不知道这两者之间的区别将会产生一个问题

def mutate(myList):
    myList = myList + ["2"] # WRONG way of doing the mutation
tList = ["1"]
mutate(tList)
print(tList)

you will still get ['1'], but if you really want to mutate myList, you could have done like this

你仍然会得到['1'],但是如果你真的想要改变myList,你可以这样做

def mutate(myList):
    myList += ["2"] # Or using append function
tList = ["1"]
mutate(tList)
print(tList)

will print ['1', '2']

将打印(' 1 ',' 2 ')