Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading