+ 2

Python - passing arguments to a function

Why, when you call f for the second time (f(range(5))), "arr" generated by first call (f(range(4))) is passed to f? def f(values,arr=[]): for i in values: if i%2==0: arr.append(i) print(arr) print(len(arr)) print("--------") return len(arr) print(f(range(4))+f(range(5)))

14th Feb 2020, 5:16 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
3 ответов
+ 6
In the way your variable arr=[] is declared, it works as a persistent variable with a kind of memoization. This means, the variable will NOT be reset if the function call is repeated. The lifetime of the variable will only end if the program is terminated. To get rid of this effect, move the initialization of arr from the function header to the first line of the function body.
14th Feb 2020, 8:38 PM
Lothar
Lothar - avatar
+ 3
All the calls used the 1 same list.
14th Feb 2020, 5:38 PM
Seb TheS
Seb TheS - avatar
+ 2
I'm a beginner so I can be wrong but I think the variables generated by a function are local/temporary variables so everytime you call that function again the values will reset (the list is same, just the values reset for every call) unless you declare the variable as a global variable.
14th Feb 2020, 5:31 PM
Utkarsh Sharma
Utkarsh Sharma - avatar