Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Created December 16, 2024 22:44

Revisions

  1. jonocarroll created this gist Dec 16, 2024.
    25 changes: 25 additions & 0 deletions py_mutable_args.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    >>> 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]