Mutable Default Arguments In Python
In this article, I’m going to mention about a very lesser known concept known as Mutable Default Arguments in Python.
Let’s look at below lines of code to understand this concept.
def AppendItems(element, lst=[]):
lst.append(element)
return lst
In above code snippet, I created a function named AppendItems, which takes two arguments a.k.a. parameters. Here 2nd argument is the list, which is also a default argument. In next line, I’m just appending items to the list and then returning the list.
Pretty simple, isn’t it?
Next, I’ll create 2 instances list1 and list2 and make call to AppendItems as shown below:
list1 = AppendItems(100)
print(list1)
list2 = AppendItems(200)
print(list2)
On executing this code, you will get some unexpected output.
If you are thinking that output will be 100 in list1 and 200 in list2, then you are wrong :(
Output of above code would be:
[100]
[100,200]
This magic is happening all because of these mutable defaults. Do watch out my below referenced video to know more details about this magic and continue…