Using a default value of None to redefine a mutable object

If you want a function to redefine a list as empty each time you call it, use a default parameter of mylist=None. None is immutable, so the function won't be referring to a list object that might change.

The following code gives the parameter mylist a default value of None in its def statement and then redefines mylist as an empty list inside the function:

def f(a, mylist=None): if mylist is None:

mylist = [] mylist.append(a) return mylist

When you call the above function several times, it doesn't accumulate arguments:

Was this article helpful?

0 0

Post a comment