I was trying to find a solution to mutate a list by passing it to the function as an argument. For example:
def f(x):
x = x*2
x = [9,8,7]
f(x)
print(x)
I want the result to be:
[9, 8, 7, 9, 8, 7]
but it ended up like this:
[9, 8, 7]
and then I stumbled with this thread: https://stackoverflow.com/a/31359713/13275449
The solution works wonderfully
def f(x):
x[:] = x*2
x = [9,8,7]
f(x)
print(x)
[9, 8, 7, 9, 8, 7]
My question is why we need the [:] ? I thought its the other way around, If we dont want to mutate the original list, we put [:] after it to copy it. But this one seems to be the opposite. It probably has something to do with global and function scope. I tried to use the pythontutor but still confused.
Thank you!
EDIT: semicolon -> colon