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