+ 1
Why does the Len(arr) return 7
Won't the function call for f(range(5)) result into initialization of another arr with Len=0 and that led to arr of Len=3 and print sum of Len of array =5 . Why does the arr have elements [0,2,0,2,4,0,2,0,2,4] when we return the arr. What is the logic of the execution of the function? https://code.sololearn.com/cR2GvEyC55O1/?ref=app
5 ответов
+ 3
This is a gotcha when using mutable types as a value for a default parameter. In order to avoid this use None and then check inside the function if the parameter is equal to None. If so then you can set the local variable to an empty list.
def example(v, arr=None):
if arr is None:
arr = []
....
....
+ 3
Thanks Bagon ,ChaoticDawg
+ 1
Thanks Bagon
0
Why does on returning the array it returns [0,2,0,2,4,0,2,0,2,4]