Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Created December 16, 2024 22:44
Show Gist options
  • Save jonocarroll/ff1c1552445cc830acdf9e59de539a6e to your computer and use it in GitHub Desktop.
Save jonocarroll/ff1c1552445cc830acdf9e59de539a6e to your computer and use it in GitHub Desktop.
Example of python's mutable arguments being mutated
>>> def make_a_list(val1 = 0, val2 = 0, lst = []):
... lst.append(val1)
... lst.append(val2)
... return lst
>>> # you need to know that you're modifying base_list
>>> base_list = [1, 2, 3, 4]
>>> extend_list = make_a_list(5, 6, base_list)
>>> print(extend_list)
[1, 2, 3, 4, 5, 6]
>>> # so it's now the same as extend_list
>>> print(base_list)
[1, 2, 3, 4, 5, 6]
>>> # good luck if you don't know it's referenced
>>> # in this case lst = [] is defined at
>>> # function definition and is mutable
>>> my_list = make_a_list(3, 4)
>>> print(my_list)
[3, 4]
>>> other_list = make_a_list(7, 8)
>>> print
[3, 4, 7, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment