The code is passed an array. My understanding is this passing is done by reference. I want the function to recursively divide the last remaining half of the list in two and set each value that it was split at to zero.
The change to zero is happens in the array but when I call print a at the end I get the original array.
What am i doing wrong?
a = range(10)
if len(array) == 1:
array = 0
split = len(array)/2
array[split] = 0
[0, 1, 2, 3, 4, 0, 6, 7, 8, 9]
This is probably what you want.
a = range(1, 10) def list_reduction(l, prev_split_pos=None): split_pos = (len(l) + prev_split_pos) / 2 if prev_split_pos else len(l) / 2 if split_pos == prev_split_pos: return l[split_pos] = 0 return list_reduction(l, split_pos) list_reduction(a) print a
So, to your code. Everytime you do a list slice, you actually generate a new list, which is not at all connected to the old one. This is why you don't see any mutations to it except the first one.