Function using list in Python

Hi there,
I am a little bit confused as I am trying to use very simple functions on lists.
My code is:

def function_list(l):
l[0] = “C”
return l

list_1 = [“A”, “B”]

list_2 = function_list(list_1)

and it returns
[‘A’, ‘B’]
[‘C’, ‘B’]

Can anyone explain why list_1 gets modified even tho the function is called on list_2 ?
What should be the code in order not to modify list_1 ?

Thanks for your responses.

  1. Magic word: mutable :wink:
  3. It could be nice if you find a way to format your code
  4. This is a general programming question. I would look for an answer on more general forums (=> stack :wink:)

In your function:

clone = [*l]
clone[0] = “C”
return clone

As said before, list are mutables so you need to copy your list before any modification.
Note that I did a shallow copy here cause it’s enough for this case but if you work with a list of mutable objects (e.g. list of lists), you need a deeper copy.