Why is the function argument populated? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why is the function argument populated?

In the following code the arr argument has a non default value in the second call to f. Can someone explain why? def f(values,arr=[]): print(arr) for i in values: if i % 2 == 0: arr.append(i) print(arr) return len(arr) print(f(range(4))) # prints 2 # print(arr) --> not defined print(f(range(5))) # prints 5 # why does the second call to f have arr initialized to [0, 2] rather than to []? https://code.sololearn.com/cuQNwWgv8Yc0/?ref=app

17th Jun 2018, 10:57 AM
Harm
4 Answers
+ 1
Paul Jacobs, thanks for your further remarks, which helped me to browse stackoverflow more targeted. Based on what I found there I derive the explanation is as follows: argument arr is a pointer to an array which gets initialized when the function is defined. In arr.append call the array to which arr points is changed, meaning it is updated for every call that you make. You cannot normally store data in local variables across function calls, e.g. if arr would be of type integer you cannot push updates to the next call.
17th Jun 2018, 5:46 PM
Harm
+ 4
You have used arr before. You can put one of these lines in your function to solve the problem: arr.clear() arr=[]
17th Jun 2018, 12:02 PM
Paul
Paul - avatar
+ 4
If you use a function more than once you could leave something behind in the local variables. That is what you do. In both codes below the problem is solved: #it works like this. def f(values, arr=[]): arr.clear() print(arr) for i in values: if i % 2 == 0: arr.append(i) print(arr) return len(arr) print(f(range(4))) # prints 2 # print(arr) --> not defined print(f(range(5))) # prints 5 # And it works like this. def f(values): arr=[] print(arr) for i in values: if i % 2 == 0: arr.append(i) print(arr) return len(arr) print(f(range(4))) # prints 2 # print(arr) --> not defined print(f(range(5))) # prints 5
17th Jun 2018, 4:19 PM
Paul
Paul - avatar
0
Paul Jacobs, my question is why it is not [] in the first place in the scope of the second call. arr is unknown in the outer scope. putting arr.clear() there gives an error.
17th Jun 2018, 3:20 PM
Harm