+ 2

Explain the output of this code.

I didn't able to understand the output of the following code. I read it some where. Thanks for output explanation. https://code.sololearn.com/cFn9qCjl8XY6/?ref=app

16th Mar 2019, 6:06 AM
AKS
AKS - avatar
6 Answers
+ 6
The first call of func(10) changes the function's default parameter from [] to [10]. Each further function call keeps changing the default parameter. So unless this is what you want, [] shouldn't be used as a default parameter
16th Mar 2019, 6:38 AM
Anna
Anna - avatar
+ 3
Lothar But the output is different my friend it come list1=[10, 'a']
17th Mar 2019, 3:07 PM
AKS
AKS - avatar
+ 2
Anna mam What is the role of [] In list 2. Why list 2 is print different
16th Mar 2019, 6:46 AM
AKS
AKS - avatar
+ 2
hi Anna, hi Adevil, it takes me a while to check what the output shows because for me it looks not logical. List1 can not contain an ‘a’ as this is used later. For me it looks like that using list[] from function header is given back with ‘return’ as a reference. When I changed the way to return this list by a ‘deep’ copy with a slice, result will as expected. def func(val, list=[]): list.append(val) return list [:] list1 = func(10) list2 = func(123,[]) list3 = func('a') print ("list1 = %s" % list1) print ("list2 = %s" % list2) print ("list3 = %s" % list3) output will then be: list1 = [10] list2 = [123] list3 = [10, 'a']
16th Mar 2019, 12:51 PM
Lothar
Lothar - avatar
+ 2
hi all, I have been doing an other test to demonstrate what the code is doing. The code itself is nothing very special but test shows that investigating to find reasons can take time. https://code.sololearn.com/cp8PXdHew6c0/?ref=app
17th Mar 2019, 3:02 PM
Lothar
Lothar - avatar
+ 2
ADEVIL, yes that is right. You can find it my code in section ‘Version-1’. But how can list1 contain ‘a’. This character is used much later in the code sequence.
17th Mar 2019, 5:30 PM
Lothar
Lothar - avatar