Python 3.8: 为什么 new_list 被更新,即使 if 语句是假的?

Python 3.8: Why is new_list being updated even though if statement is false?

我是 python 的初学者,我想知道为什么在下面的代码中,即使 new_list 是只有当我的 if 条件为真时才应该更新(这就是我想要的)。

my_sum = 0
first_list = [1, -2, 3, -4]
second_list = []
new_list = []

for num in first_list:
    second_list.append(num)
    if my_sum <= sum(second_list):
        my_sum = sum(second_list)
        new_list = second_list
    print(new_list)

输出:

[1]
[1, -2]
[1, -2, 3]
[1, -2, 3, -4]

但是,当我将 print 语句移到 if 语句中时,我在每次 for 循环迭代结束后得到了预期的结果:

my_sum = 0
first_list = [1, -2, 3, -4]
second_list = []
new_list = []

for num in first_list:
    second_list.append(num)
    if my_sum <= sum(second_list):
        my_sum = sum(second_list)
        new_list = second_list
        print(new_list) # Moved print statement inside if statement

输出:

[1]
[1, -2, 3]

有人可以解释为什么 new_list 在每次 for 循环迭代后更新,即使我只希望它在我的 if 条件为真时更新吗?

提前致谢!

您在表达式 new_list = second_list 中将 new_list 别名为 second_list。基本上,在这一行之后,它们都是同一个实体。相反,您想做类似 new_list = second_list.copy().

的事情