修改列表元素会意外更改其引用的原始列表

时间:2018-07-22 12:23:24

标签: python list string.format

编辑:根据回答澄清问题

当我创建一个列表并使用for循环和.format-Function用另一个列表中的内容填充其元素时,原始列表中的值也会更改。我认为当您运行下面的代码(示例1)并阅读打印的语句时,行为很清楚。

但是,在示例2中无法观察到这种行为。为什么?

Python版本:3.6.5

非常感谢!

示例1:

list = [i for i in range(5)]

print("The variable 'list' is ", end='')
print(*list)
print()

new_list = list

print("A new variable 'new_list' is created and gets assigned the values from 'list' and is ", end='')
print(*new_list, end='')
print(" as well")
print("The variable 'list' is still ", end='')
print(*list)
print()

print("Each element in 'new_list' gets modified by using a for loop and the '.format-Function")

for column in range(5):
    new_list[column] = "X{}".format(list[column])

print("The variable 'new_list' is now ", end='')
print(*new_list)
print()

print("Why did this change the variable 'list'? It is now ", end='')
print(*list, end='')
print(" as well?!")

示例2:

A = ["A0", "A1"]

print ("A = {}".format(A))

B = ["B0", "B1"]

print ("B = {}".format(B))

B[0] = "X{}".format(A[0])
B[1] = "X{}".format(A[1])

print ("A = {}".format(A))
print ("B = {}".format(B))

0 个答案:

没有答案