+ 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
4 Réponses
+ 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.
+ 4
You have used arr before.
You can put one of these lines in your function to solve the problem:
arr.clear()
arr=[]
+ 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
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.