How to update list recursively

Iterative and in place solution

a = [{'one': 1}, {'two': 2}, {'three': 3}, {'four': 4}, {'five': 5}]
sum_so_far = 0
first_flag = False
for i in a[::-1]:
    k,v = i.items()[0]   #For Python 3 k,v = list(i.items())[0]
    sum_so_far += v
    if first_flag:
        i[k] = sum_so_far # do not change the value at first

    first_flag=True

Output

[{'one': 15}, {'two': 14}, {'three': 12}, {'four': 9}, {'five': 5}]

Your problem comes from the output of a.pop(0). A.pop(0) returns the element at 0, not the list without the element at 0. Therefore, when you call recursively, you are indexing on a dict, rather than a list. What do you expect to be inputting into the recursive call?

I would guess you are trying to remove the 0th index, then call recursively. To do this,

a.pop(0);
return val + recursive(a)

edit: a note - key error 0 means you are indexing a dict with key 0 when key 0 does not yet exist.

Tags:

Python