samedi 22 mai 2021

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

I am a beginner in python and I am wondering why, in the following code, new_list is being updated after each iteration of the for-loop even though new_list is only supposed to update when my if condition is true (this is what I want).

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)

Output:

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

However, when I move the print statement inside the if statement, I get the result I expect after the conclusion of each for-loop iteration:

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

Output:

[1]
[1, -2, 3]

Can someone please explain why new_list updates after each for-loop iteration, even though I only expect it to update when my if condition is true?

Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire