Search code examples
listfunctionglobal-variablesvariable-assignment

List variable assignment inside a function causing unwanted change to the global variable


I am trying to create a copy of a list inputted into a function, then reassign one of the copied list's values, then return the new list.

w is returned correctly as I would expect. However, when I run this function it changes my original list.

a = [[0,1],[2,3]]

def func(l):
    w = l
    w[0][0] = 55
    
    return w
        
func(a)

print(a)
Output: [[55, 1], [2, 3]]

I would want to see:

func(a)

print(a)
Output: [[0, 1], [2, 3]]

I had thought that anything changed inside the function would not affect the global variable. How do I get the function to return w (with the reassigned value) without changing a?


Solution

  • You're just making another reference to the list, you are not actually creating a new variable.

    use the copymodule

    import copy
    a = [[0, 1], [2, 3]]
    
    
    def func(l):
        w = copy.deepcopy(l)
        w[0][0] = 55
    
        return w
    
    
    func(a)
    
    print(a)
    
    >>> [[0, 1], [2, 3]]