Fucntion scope ... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Fucntion scope ...

Came across this during a challenge: def f(values, arr = []): for i in values: if i%2 == 0: arr.append(i) return len(arr) print(f(range(4))+f(range(5))) I understand passing range(4) to f and that arr=[] is default since there is nothing passed as a second parameter. My question is when range(5) is passed to f. My logic tells me that the scope of arr should have expired after the first return and set to [] during the second calling of f. but that does not seem to be the case. Could someone please shed some light on how the scope off arr works here? Thank you

12th Jan 2020, 5:03 PM
GeoK68
GeoK68 - avatar
1 Answer
+ 3
The behavior of arr in this case is a kind of memorization. This happens if a list is declared in this way in the function header. Even if the list has some values like "def f(values, arr = [1,2,3]):" it will have this behavior. So if the function is called the first time, it gets initialized by either the values from the header or the values that may be passed with the function call. With each further call, the values ​​in the list are the same as when the function was last exited. The list will keep alive as long as your program is running.
12th Jan 2020, 7:02 PM
Lothar
Lothar - avatar