Categories

Dec 14, 2019 in Python
Q: What Is The Output Of The Following Python Code Fragment?

def extendList(val, list=[]):

    list.append(val)

    return list

list1 = extendList(10)

list2 = extendList(123,[])

list3 = extendList('a')

print "list1 = %s" % list1

print "list2 = %s" % list2

print "list3 = %s" % list3

1 Answer

Dec 14, 2019
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']
Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
May 17, 2019 in Python
Jun 13, 2019 in Python
Jun 13, 2019 in Python
...