What is the difference between fun1 and fun2 ? Why arr in fun1 have old memory of first call while calling second time? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

What is the difference between fun1 and fun2 ? Why arr in fun1 have old memory of first call while calling second time?

#Code: def fun1(val, arr=[]): for i in val: arr.append(i) return len(arr) def fun2(val): arr = [] for i in val: arr.append(i) return len(arr) print(fun1(range(4))+fun1(range(5))) print(fun2(range(4))+fun2(range(5))) #Output: 13 9

8th Sep 2017, 9:50 AM
⚛prudhvi⚛
⚛prudhvi⚛ - avatar
2 Answers
+ 3
In fun2 arr = [] resets the variable arr to an empty list each time the function is called. In fun1 arr is a parameter that will have a default of an empty list if arr is not already set or a value has not been previously passed. If you pass an empty list [] with the second call to fun1 the result will be the same as it is with fun2. print(fun1(range(4))+fun1(range(5), [])) Or change fun1 as follows: def fun1(val, arr=None): if arr == None: arr = [] for i in val: arr.append(i) return len(arr) http://docs.python-guide.org/en/latest/writing/gotchas/
8th Sep 2017, 10:20 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
@ChaoticDawg, thank you👍
8th Sep 2017, 10:31 AM
⚛prudhvi⚛
⚛prudhvi⚛ - avatar