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

19th Apr 2019, 1:08 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
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’.
19th Apr 2019, 4:07 AM
Rowsej
Rowsej - avatar
+ 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.
19th Apr 2019, 5:19 AM
Anna
Anna - avatar
+ 2
Thanks! Anna
19th Apr 2019, 6:26 AM
Thimira Rathnayake
Thimira Rathnayake - avatar
+ 2
Thanks! Rowsej
19th Apr 2019, 6:27 AM
Thimira Rathnayake
Thimira Rathnayake - avatar