0

I have the following problem: I have noticed that when I pass a list to a function and I append some values to that list, not just the list inside the function is modified but also the original list. However, it is well known that this does not happen to "common" variables. Here there is some code that you can try on your own. I used classes because I'm using them for a specific application, but you can forget :

class HasLeak():
    def __init__(self):
        self.tmp_list = []
        

class MainClass():
    def __init__(self):
        return
    
    def main_function(self,object_):
        object_.tmp_list.append(1)
        return
    
    def main_function_list(self,variable):
        variable.append(1)
        return
    
    def main_function_variable(self,variable):
        variable+=1
        return
    

if __name__=='__main__':
    object_leak = HasLeak()
    
    print (object_leak.tmp_list)
    mc = MainClass()
    mc.main_function(object_leak)
    print (object_leak.tmp_list)
    
    list_ = []
    print (list_)
    mc.main_function_list(list_)
    print (list_)
    
    
    variable = 0
    print (variable)
    mc.main_function_variable(variable)
    print (variable)

The output obtained is

[]
[1]
[]
[1]
0
0

while I would expect

[]
[]
[]
[]
0
0 

Is this a normal behaviour in python? How can I avoid it?

  • This is completely normal behavior. Why did you *expect* otherwise? – juanpa.arrivillaga Jun 16 '22 at 17:17
  • The linked duplicate topic might not seem like a good fit, but the accepted answer is very detailed and should address this question directly. – juanpa.arrivillaga Jun 16 '22 at 17:18
  • "However, it is well known that this does not happen to "common" variables. " This is not well-known at all, since it is false. Passing objects to functions **always** works the exact same way - you get a reference to the same object. Now, some object might be *immutable*, so you cannot mutate them, so obviously, they aren't mutated anywhere. But the behavior is always the same with regards to Python's [evaluation strategy](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing) – juanpa.arrivillaga Jun 16 '22 at 17:20
  • take a look at this video, it explain this: [Facts and Myths about Python names and values](https://www.youtube.com/watch?v=_AEJHKGk9ns) – Copperfield Jun 16 '22 at 17:34

0 Answers0