[Solved] Why don't all list elements get zeroed in this code? | SoloLearn: Learn to code for FREE!

+4

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

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

3/5/2021 11:14:25 PM

Sonic

18 Answers

New Answer

+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) ;)

+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 ;)

+2

visph so I guess, the following is the way to achieve my desired outcome then. https://code.sololearn.com/cD8D3a49UxD6/?ref=app

+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 ^^

+2

yes, your solution is valid too, but you doesn't need to return the Recursion call results ;)

+2

with this one, you print another list inside 'recurs' function, but global list 'a' after recursion is [2,3,4] ;)

+2

Lol, i am not after a completely new list but the original one modified. But thanks for trying.

+1

The list ids are the same before and after recursion.

+1

visph so list arguments are pass by value in Python? different from Java?

+1

visph I see. It's the slicing that causes the copy. I think I get it now.

+1

visph yes I know that a simple loop is more efficient. This was just a study of recursion.

+1

visph merçi beaucoup.

+1

avec plaisir :D

+1

solvermad but if you do so, the array will be empty at end of recursion ^^

+1

jeez, i just cant win

+1

its a good code, trying to solve it i learned about the nonlocal keyword & scoping, but i coulnt make them work for your problem. still its a nice code Sonic

0

inside the else statement you could do... a.remove(a[0]) print(id(a)) Recurse(a)

0

def recurs(a): a.pop() a = [0] + a if a == [0,0,0,0]: return print(a) else: (recurs(a)) a = [1,2,3,4] recurs(a)