-2

When I re-create a list variable within a different method/function, I noticed that the variable gets treated as an entirely new variable. Why is this the case? Below is an example of what I am trying to understand. If someone can explain or re-direct me to the concept I am not understanding, that would be appreciated.

class Solution():
    def first_function(self):
        triplets = [1,2,3]
        self.second_function(triplets)
        #self.third_function(triplets) #The third function works as expected. The list values get updated.
        return sum(triplets)
    
    def second_function(self,triplets):
        #setting the triplets variable to a new list of 0 values apparently creates a brand new list instead of re-using the old memory address of the 'triplets' variable that was passed in the parameter.
        triplets = [0,0,0]

    def third_function(self,triplets):
        triplets[0] = 0
        triplets[1] = 0
        triplets[2] = 0


test = Solution()
print(test.first_function()) #expecting 0 but returns 6
24SVEN
  • 19
  • 6

1 Answers1

0

Because triplets is local variable in second_function method. For re-create class variable call it from self like this:

self.tripes = [0, 0, 0]
BigCubeCat
  • 170
  • 8
  • That's what I don't understand. Why does it get switched to a local variable when in the third function it does not? Also modifying the second function to self.triplets = [0,0,0] does not work either. It still returns 6 – 24SVEN Feb 28 '22 at 09:00