About list return behaviour

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)

Hey @mdiqbal, the ambiguity lies in the lines, list1 = extendList(10) and list3 = extendList(‘a’). Actually when you do not pass the second parameter, than both the statements, receive the same list address, and hence both 10 and ‘a’ are added to same list. You can cross verify this by,

def extendList(val, list=[]):
  list.append(val)
  print(hex(id(list)))  # to print the memory address of list variable
  return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList("a")
print ("list1 = %s" % list1)
print ("list2 = %s" % list2)
print ("list3 = %s" % list3) 

Hope this resolved your doubt.
Plz mark the doubt as resolved in my doubts section. :blush:

1 Like

Resolved and thanks for the solution

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.