ASK - ANSWER - COMMENT - VOTE

MathsGee is Zero-Rated (You do not need data to access) on: Telkom |Dimension Data | Rain | MWEB

0 like 0 dislike
221 views
What is the output of the following Python code fragment? Justify your answer.
| 221 views

## 1 Answer

0 like 0 dislike
Best answer
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

The result of the above Python code snippet is:

list1 = [10, 'a']
list2 = 
list3 = [10, 'a']

You may erroneously expect list1 to be equal to  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 = 
list2 = 
list3 = ['a']

by Bronze Status (8,022 points)

0 like 0 dislike
1 answer
0 like 0 dislike
0 answers
0 like 0 dislike
0 answers
0 like 0 dislike
0 answers
0 like 0 dislike
0 answers