+ 3
Could anyone explain this function,please?
def func(a,L=[]): L.append(a) return L print(func(1),func(3)) Why this function returns [1,3][1,3] , i thought it has to return [1][3]
6 Respostas
+ 3
Ok here we go for a second try 🔥🔥
I totally agree with you that after each call of a function all local variables are destroyed.
keep in mind that a default argument value is not destroyed after the function call instead your function will always know where the are stored in memory.
let's go
first function call
1. func(1) # will create that list in memory and pass the reference to the L argument.
first call over ok destroy a, and L(but remember L holds a ref to the list) so the list still in memory and the function knows about it since he made the initialisation in the first call.
value of the array is changed to [1]
Second call
2. func(3) instead of creating a new list and pass it to the L argument, the function will return the reference of the one he created in his first call.
which equals to [1]
so the default argument value in the second call is not [] but [1].
and then he append 3 to that list -> [1,3]
This is why you get that result at the end.
Hope this make things clear 😄😄
+ 1
Functions default argument are initialized once .
So in your first call the default argument is initialized to the array and one is added to it.
then in the second call the same array is reused and its already hold your first value and the second value is added.
That why you get [1,3] to the end.
+ 1
def func(a, L=[]):
L.append(a)
return L
print(func(1, func(3)))
Try above code it prints
[3, 1]
It makes clear that initialised value is never gets deleted
Here query is that it should be deleted.
Going to try on two different lines. Does it makes sense.
Tried,
def func(a, L=[]):
L.append(a)
return L
print(func(1))
print (func(3))
it prints [1, 3]
As per my knowledge it is not according to design will try one more test case.
DHANANJAY
+ 1
def func(a, L=[]):
L.append(a)
return L
print(func(1))
print(func(3, [1]))
print(func(2, [5]))
print(func(4, [6]))
print(func(7))
It prints
[1]
[1, 3]
[5, 2]
[6, 4]
[1, 7]
Is it understandable and according to design.
DHANANJAY
0
Alpha Diallo
I didn't get it 😁
They say the local variable gets destroyed after returning its value.
So in the first call it returns [1]
And in the second call it returns [3]
0
Alpha Diallo
Thanks you very much 🙏
I really appreciate your effort