+ 4

# [Solved] Why don't all list elements get zeroed in this code?

https://code.sololearn.com/ckf1H17schnP/?ref=app

5th Mar 2021, 11:14 PM
Sonic
+ 4
no: primitives are passed by values, while objects are passed by references ^^ that's why only the first item is set to zero: the list id at the initial recursion call remain the same, but each other call pass the sliced list (wich is a copy) ;)
5th Mar 2021, 11:35 PM
visph
+ 3
in 'Recurse' function you're trying to write in argument and you return nothing: a remain holding the same list/memory adress. only first item of list is set to zero, because the fact is that at each recursion steps, you're passing a copy of the argument list subset (slicing): you could print(id(a)) before Recursion call inside Recursion ;)
5th Mar 2021, 11:30 PM
visph
+ 2
visph so I guess, the following is the way to achieve my desired outcome then. https://code.sololearn.com/cD8D3a49UxD6/?ref=app
5th Mar 2021, 11:43 PM
Sonic
+ 2
to recursively set to zero all items of a list, rather use something like: def Recurse(a,i=0): if i != len(a): a[i] = 0 Recurse(a,i+1) however, a basic loop would be more efficient and not limited ^^
5th Mar 2021, 11:44 PM
visph
+ 2
yes, your solution is valid too, but you doesn't need to return the Recursion call results ;)
5th Mar 2021, 11:45 PM
visph
+ 2
with this one, you print another list inside 'recurs' function, but global list 'a' after recursion is [2,3,4] ;)
7th Mar 2021, 4:58 PM
visph
+ 2
Lol, i am not after a completely new list but the original one modified. But thanks for trying.
7th Mar 2021, 8:14 PM
Sonic
+ 1
The list ids are the same before and after recursion.
5th Mar 2021, 11:15 PM
Sonic
+ 1
visph so list arguments are pass by value in Python? different from Java?
5th Mar 2021, 11:31 PM
Sonic
+ 1
visph I see. It's the slicing that causes the copy. I think I get it now.
5th Mar 2021, 11:37 PM
Sonic
+ 1
visph yes I know that a simple loop is more efficient. This was just a study of recursion.
5th Mar 2021, 11:45 PM
Sonic
+ 1
visph merΓ§i beaucoup.
5th Mar 2021, 11:48 PM
Sonic
+ 1
avec plaisir :D
5th Mar 2021, 11:48 PM
visph
+ 1
solvermad but if you do so, the array will be empty at end of recursion ^^
7th Mar 2021, 4:22 PM
visph
+ 1
jeez, i just cant win
7th Mar 2021, 4:59 PM