The result of the above Python code snippet is:
list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']
You may erroneously expect list1 to be equal to [10] and list3 to match with [‘a’], thinking that the list argument will initialize to its default value of [] every time there is a call to the extendList.
However, the flow is like that a new list gets created once after the function is defined. And the same get used whenever someone calls the extendList method without a list argument. It works like this because the calculation of expressions (in default arguments) occurs at the time of function definition, not during its invocation.
The list1 and list3 are hence operating on the same default list, whereas list2 is running on a separate object that it has created on its own (by passing an empty list as the value of the list parameter).
The definition of the extendList function can get changed in the following manner.
def extendList(val, list=None):
if list is None:
list = []
list.append(val)
return list
With this revised implementation, the output would be:
list1 = [10]
list2 = [123]
list3 = ['a']