Lists update unexpectedly after calling the function

Viewed 29

I write some functions to update list like this:

def list_1(list_tmp):
    list_1 = list_tmp
    list_1.insert(0, 'c')
    return list_1
def list_2(list_tmp):
    list_2 = list_tmp
    list_2.insert(0, 'd')
    return list_2

Then if I call:

my_list = ['a', 'b']
list_1 = list_1(my_list)
list_2 = list_2(my_list)
list_1, list_2, my_list

(['d', 'c', 'a', 'b'], ['d', 'c', 'a', 'b'], ['d', 'c', 'a', 'b'])

Whereas I expect my_list is the same, only 'c' is added on list_1 and only 'd' is added on list_2. Why does this happen and how should I fix it?

1 Answers

You meant to make a copy of the parameter by the looks of your code.

Did you mean:

def list_1(list_tmp):
    list_1 = list_tmp[:]
    list_1.insert(0, 'c')
    return list_1
def list_2(list_tmp):
    list_2 = list_tmp[:]
    list_2.insert(0, 'd')
    return list_2

my_list = ['a', 'b']
list_1 = list_1(my_list)
list_2 = list_2(my_list)
print(list_1, list_2, my_list)
Related