0

Python: I am a bit lost in local and global scope...

def ZeroRecursive(a): if a == []: return a[0] = 0 ZeroRecursive(a[1:]) a = [1,2,3,4] ZeroRecursive(a) # [0, 2, 3, 4] Why only the first digit will be zero in the output? I am a bit lost in local and global variables here...

15th Mar 2020, 5:23 AM
Prof. Dr. Zoltán Vass
4 odpowiedzi
+ 3
I think maybe it's because `a[1:]` is a slice, which is a different `list` object, not the actual `list` <a>.
15th Mar 2020, 7:41 AM
Ipang
+ 3
Prof. Dr. Zoltán Vass I would avoid using the same identifier for function argument and actual object to pass as argument. Especially if the actual object is global 😁 By using a different name for parameter and actual object (passed as argument), plus a little print outs, it becomes clearer which one is being modified in the function. def ZeroRecursive(b): print(f'PRE-CHECK\nList <a> is {a} and argument <b> is {b}') if b == []: print(f'Argument <b> is {b}. Leave recursion.') return b[0] = 0 print(f'POST-CHECK\nList <a> is {a} and argument <b> is {b}\n') ZeroRecursive(b[1:]) a = [1,2,3,4] ZeroRecursive(a) print(f'\nFinally List <a> is {a}') # [0, 2, 3, 4]
15th Mar 2020, 8:22 AM
Ipang
+ 2
Ipang I think so but why only the first digit of the global list is replaced by 0?
15th Mar 2020, 7:44 AM
Prof. Dr. Zoltán Vass
+ 2
Prof. Dr. Zoltán Vass The actual `list` <a> is only passed on and modified at the first recursion phase, the successive recursion phases only modifies a slice of the previous recursion phase. A slice obviously be a different `list` object, so I guess that is why only the first element of actual `list` <a> is actually getting modified.
15th Mar 2020, 9:16 AM
Ipang