pythonpython-3.xlistassign

Why does my list variable change at every loop?


Why does my variable change at every loop?

I'm training using leetcode and I found a weird problem.

There is my code:

def kidsWithCandies(candies, extraCandies: int):
    output = []
    for enfant in range(len(candies)) :
        print(candies) #Show  candies for debug
        test_candies = candies
        test_candies[enfant] = test_candies[enfant]+extraCandies
        is_great = True
        for enfant2 in range(len(test_candies)) :
            if enfant == enfant2 :
                continue
            if test_candies[enfant] < test_candies[enfant2] :
                is_great = False
        output.append(is_great)
    return output
print(kidsWithCandies([2,3,5,1,3],3))

I get this output:

[2, 3, 5, 1, 3]
[5, 3, 5, 1, 3]
[5, 6, 5, 1, 3]
[5, 6, 8, 1, 3]
[5, 6, 8, 4, 3]
[True, True, True, False, False]

The weird thing is that candies is different at every loop for no obvious reason.

Am I not understanding something?


Solution

  • You need to create a new list for test_candies, the assignment of the variable only creates a reference to the existing list.

    def kidsWithCandies(candies, extraCandies: int):
        output = []
        for enfant in range(len(candies)) :
            print(candies) #Show  candies for debug
            test_candies = list(candies) # Create a new list
            test_candies[enfant] = test_candies[enfant]+extraCandies
            is_great = True
            for enfant2 in range(len(test_candies)) :
                if enfant == enfant2 :
                    continue
                if test_candies[enfant] < test_candies[enfant2] :
                    is_great = False
            output.append(is_great)
        return output
    
    print(kidsWithCandies([2,3,5,1,3],3))