Can anybody tell Me why output Code Is 7 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can anybody tell Me why output Code Is 7

There is the code def f(values,arr=[]): for i in values: if i%2==0: arr.append(i) print(arr) return len(arr) print(f(range(4))+f(range(5))) Can anybody tell me, what i dont understand why output code is 7, because after all iterations we have array arr=[0,2,0,2,4] What i do wrong? https://code.sololearn.com/cWJuOJUxGSA8/?ref=app

13th Mar 2018, 6:20 PM
Никита
3 Answers
+ 20
it will be print(len([0,2])+len([0,2,0,2,4])) i hope u will understand now
13th Mar 2018, 6:32 PM
🌛DT🌜
🌛DT🌜 - avatar
+ 8
I had a similar question a while back and the following reply from John Wells was the best https://docs.quantifiedcode.com/JUMP_LINK__&&__python__&&__JUMP_LINK-anti-patterns/correctness/mutable_default_value_as_argument.html
13th Mar 2018, 6:32 PM
Louis
Louis - avatar
+ 2
This happens because after you call f(range(4)), your array keeps the two values added. So it already has length 2. Now, when you run f(range(5)) three more values are added and now f(range(5)) will return 5. So you end up with 7. What you should do is maybe pass an empty array to f every time it is called
13th Mar 2018, 6:32 PM
cyk
cyk - avatar