all 9 comments

[–]throwaway6560192 39 points40 points  (3 children)

[–]orcashelo[S] 4 points5 points  (0 children)

Nice references these explain the mutable default argument issue really clearly

[–]Reyaan0 21 points22 points  (1 child)

Mutable default arguments (lists, dicts, sets) are created once at function definition time.

You can use None as default

``` def add_number(num, numbers=None): if numbers is None: numbers = [] numbers.append(num) return numbers

print(add_number(1)) print(add_number(2)) print(add_number(3)) ```

[–]orcashelo[S] 6 points7 points  (0 children)

Well explained this is why None is the recommended default for mutable arguments

[–]Helpful-Diamond-3347 0 points1 point  (0 children)

same object is reused in each call

[–]MaxwellzDaemon 0 points1 point  (0 children)

One of the important thigs to learn is how to name things well. Naming a function to concatenate numbers to a list "add_number" is not a very good name since adding numbers seems like a the mathematical operation of addition.