0

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?

Sentinel
  • 261
  • 1
  • 8

1 Answers1

0

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]]
coderoftheday
  • 1,987
  • 4
  • 7
  • 21
  • Thank you! I still don't know why creating another variable name doesn't create a copy for lists or dictionaries (as would normally happen with other data types like int or str) but the copy module fixed my problem – Sentinel Dec 03 '20 at 23:46
  • @Sentinel see https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent – coderoftheday Dec 04 '20 at 09:50