+ 1
Why does this give [0,2,3,4] as output instead of [0,0,0,0]?
def z(a): if a == []: return a[0] = 0 z(a[1:]) a = [1,2,3,4] z(a) print(a)
4 Respuestas
+ 7
I’m not sure, but maybe because you’re using a as the list and as the function parameter, maybe it’s referring to the list ‘a’ instead of the function parameter ‘a’.
+ 4
You're calling z(a) with the argument a = [1, 2, 3, 4]. Is a an empty list? No. So you set a[0] to 0 and a is now [0, 2, 3, 4]. Your changes affect the original list (which is also called a, but that doesn't make any difference, it just makes your code harder to read and maintain).
Then you're calling the same function with the slice a[1:] which is a new list and doesn't affect a. So the recursive function calls don't change the original list.
+ 2
Thanks! Anna
+ 2
Thanks! Rowsej