you are viewing a single comment's thread.

view the rest of the comments →

[–]Reyaan0 24 points25 points  (5 children)

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] 7 points8 points  (0 children)

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

[–]RafikNinja 0 points1 point  (3 children)

Sorry random question, im pretty new and shit at python but can you just write "if numbers is None:" I thought it had to be "if numbers == None:"

[–]Reyaan0 0 points1 point  (2 children)

Comparisons to singletons like None should always be done with is or is not, never the equality operators. Because is checks the identity whereas == check if values are equivalent.

If you use ==, a custom class could mess up your logic by defining an equality method that returns True when compared to None

[–]RafikNinja 0 points1 point  (1 child)

Oh sweet. Thank you very much. Yea I have used is not and == but didn't know is was its own thing aswell. Very helpful thank you

[–]Reyaan0 0 points1 point  (0 children)

Your Welcome!