0

I try this simple code:

def chage_value(dict, key):
    dict[key] = 123
    return dict


my_dict = {'a': 1, 'b': 2}

print(my_dict)

chage_value(my_dict, 'a')

print(my_dict)

This gives me output:

{'a': 1, 'b': 2}
{'a': 123, 'b': 2}

Why ‘a’ value changed? I didn’t do something like my_dict = chage_value(my_dict, 'a')

garik f
  • 37
  • 5

1 Answers1

2

You were mutating the arguments thats why, for example see this

def add_to(num, target=[]):
    target.append(num)
    return target

add_to(1)
# Output: [1]

add_to(2)
# Output: [1, 2]

add_to(3)
# Output: [1, 2, 3]

You might be expecting that a fresh list would be created when you call add_to, but thats not the case. You mutate the argument, this is what you want to do when you don't want it to mutate the argument

from copy import deepcopy
def foo(some_var):
    some_var_ = deepcopy(some_var)
    ...
    return some_var_

Here you mutate the copy of some_var instead of the original.

You can see here what are the other mutable things. https://book.pythontips.com/en/latest/mutation.html#mutation

Ibrahim
  • 798
  • 6
  • 26