1

I came across this below Python code which is showing an unexpected behavior.

def extendList(val, list=[] ):
    list.append(val)
    return list

list1 = extendList(10)
print "value of list1 before = %s" % list1

list2 = extendList(123,[])
list3 = extendList('a')

print "value of list1 after = %s" % list1    

According to me, the expected output of this code should be:

value of list1 before = [10]
value of list1 after = [10]

The actual output of this code is:

value of list1 before = [10]
value of list1 after = [10, 'a']

I am not sure why list1 would change its value later when list3 is being assigned and append 'a' to its current value i.e. [10].

Anoop Sharma
  • 87
  • 1
  • 13

0 Answers0