i was coding this code and noticed something weird, after my function has been called on the variable, the value of the variable gets changed although its outside of the functions scope, how exactly is this happening?
def test(my_list):if 11 in my_list and sum(my_list) > 21:my_list.remove(11)my_list.append(1)return sum(my_list)ca = [11,11]
print(test(ca))
print(ca)
the above code results to:
12
[11, 1]
Because my_list is a list, a mutable object.
https://docs.python.org/3/faq/programming.html#why-did-changing-list-y-also-change-list-x
In other words:
If we have a mutable object (list, dict, set, etc.), we can use some specific operations to mutate it and all the variables that refer
to it will see the change.
If we have an immutable object (str, int, tuple, etc.), all the variables that refer to it will always see the same value, but
operations that transform that value into a new value always return a
new object.
https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
3. By passing a mutable (changeable in-place) object:
>>>>>> def func2(a):
... a[0] = 'new-value' # 'a' references a mutable list
... a[1] = a[1] + 1 # changes a shared object
...
>>> args = ['old-value', 99]
>>> func2(args)
>>> args
['new-value', 100]
You can change the content of a list, but not a list itself. For example:
>>> def test(my_mutable):
... my_mutable = [1]
... print(my_mutable)
...
>>> my_mutable = [2]
>>> test(my_mutable)
[1]
>>> my_mutable
[2]
You can do the same with dict:
>>> ca = {11: 11, 12: 12}
>>> def test(my_dict):
... if 11 in my_dict and sum(my_dict.values()) > 21:
... del my_dict[11]
... my_dict[1] = 1
... return sum(my_dict.values())
...
>>> test(ca)
13
>>> ca
{12: 12, 1: 1}