Sitemap

Python: Beware of mutable default arguments

1 min readSep 25, 2024

--

Press enter or click to view image in full size

While mutable default arguments don’t directly cause memory leaks in Python, they can lead to unexpected behaviour. Here’s an example that demonstrates the issue:

def append_to_list(item, my_list=[]):
my_list.append(item)
return my_list

print(append_to_list(1)) # Output: [1]
print(append_to_list(2)) # Output: [1, 2]
print(append_to_list(3)) # Output: [1, 2, 3]

Explanation:

  • The default value for my_list is evaluated only once when the function is defined, not each time it's called.
  • This means that the same list is used across all calls to the function if you don’t provide a different list as an argument.
  • As a result, the list keeps growing with each call.

How to avoid this:

Get Ankur Bansal’s stories in your inbox

Join Medium for free to get updates from this writer.

The standard way to avoid this unexpected behaviour is to use None as the default value and create a new list inside the function if needed:

def append_to_list(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list

print(append_to_list(1)) # Output: [1]
print(append_to_list(2)) # Output: [2]
print(append_to_list(3)) # Output: [3]

--

--