How do I change list2 without changing list1 in from a function in Python?

def change_list(ls):
    ls1 = ls
    ls1[1] = "?"
    return ls1

list1 = ['a', 'b', 'c', 'd']
list2 = change_list(list1)

print(list1)
print(list2)

Result:

List 1 - ['a', '?', 'c', 'd']
List 2 - ['a', '?', 'c', 'd']

Expected Result:

List 1 - ['a', 'b', 'c', 'd']
List 2 - ['a', '?', 'c', 'd']

>Solution :

You need to make a new list instead of modifying the original one:

def change_list(ls):
    ls1 = ls.copy()
    ls1[1] = "?"
    return ls1

Another option would be to build the new list out of slices of the original:

def change_list(ls):
    return ls[:1] + ["?"] + ls[2:]

Leave a Reply