-1
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']
Zac Anger
  • 6,983
  • 2
  • 15
  • 42
  • 1
    You only have one list here, with two names. You would have to do something like `ls2 = ls.copy()` to make an independent list; Python never does that unless explicitly requested to. – jasonharper Apr 18 '23 at 03:37
  • 2
    Please see [this](https://stackoverflow.com/questions/2612802/how-do-i-clone-a-list-so-that-it-doesnt-change-unexpectedly-after-assignment), [this](https://stackoverflow.com/questions/67055595/how-can-i-modify-a-list-without-change-the-original-list-variable-in-python), [this](https://stackoverflow.com/questions/70315542/why-does-the-original-list-change-when-i-change-the-copied-list-python), or [this](https://stackoverflow.com/questions/41777333/how-to-reverse-a-list-without-modifying-the-original-list-in-python) – Zac Anger Apr 18 '23 at 03:38

1 Answers1

2

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:]
Samwise
  • 68,105
  • 3
  • 30
  • 44