Home > Back-end >  Should you always add list.copy() / dict.copy() when passing a list/dict to a function?
Should you always add list.copy() / dict.copy() when passing a list/dict to a function?

Time:04-22

I had a painful experience today that I accidentally passed a list to a function, and took me ages to debug. The function was meant to take in a list and create a copy of similar list. I did not realize this modified my original list.

L = [0,0,0,0,0]

def similar_list(a_list):
    a_list [0] = a_list[0] 1
    return a_list

L_similar = similar_list(L)
print(L)
print(L_similar)

#result shows
#[1, 0, 0, 0, 0]
#[1, 0, 0, 0, 0]

I think the best way is in the first line of the similar_list function, add a_list = a_list.copy(). Is there a better way to this? I am asking as in my limited study of python, I don't recall seeing this often in sample code. Would appreciate it if you could let me know if this is a standard practice. (Still, this seems a thing that is very easy to get wrong, and very hard to notice when it is wrong..)

CodePudding user response:

It all depends on what similar_list() is supposed to do.

If you intend to modify the original list, just change it in place as you've seen:

def similar_list(a_list):
    a_list[0]  = 1

As you notice, I don't return the original list. Per Python's convention, functions or methods that modify the input object, do not return it as to avoid confusion and be clearer.

If you intend to return a new list, which has numerous advantages related to immutability, you can copy and then modify:

def similar_list(a_list):
    newlist = a_list.copy()
    newlist[0]  = 1
    return newlist

It is a standard practice if you have the need to copy, but eventually it is yours to decide.

For some pros and cons you can consult with Python's official guide on functional programming.

CodePudding user response:

Instead of using L_similar = similar_list(L) you can use L_similar = similar_list(L[:]) to avoid any change in your original list.

Try this:

L = [0,0,0,0,0]

def similar_list(a_list):
    a_list [0] = a_list[0] 1
    return a_list

L_similar = similar_list(L[:])
print(L)
print(L_similar)

#result shows
#[0, 0, 0, 0, 0]
#[1, 0, 0, 0, 0]
  • Related