[Tutor] Recursive assignment in nested lists

Puneeth Chaganti punchagan at gmail.com
Sat Aug 4 09:20:03 CEST 2012


On Sat, Aug 4, 2012 at 12:28 PM, Alonzo Quijote
<alonzo.quijote at gmail.com> wrote:
> Is there a way to define a function which takes
>    a list (of lists),
>    a position specified by a list of integers [i0,i1,...,in], and
>    a value
> and returns the result of setting
>     list[i0][i1]...[in]=value
>
> The following function works for positions up to length 3 only.
> Is it possible to write a general function that does this?
>
> def setValueAtPosition(list,pos,value):
>     if len(pos)==1:
>         list[pos[0]]=value
>     elif len(pos)==2:
>         list[pos[0]][pos[1]]=value
>     elif len(pos)==3:
>         list[pos[0]][pos[1]][pos[2]]=value
>     return list

Something like this, should work :

def setValueAtPosition(my_list, pos, value):
    sub_list = my_list
    for i in pos[:-1]:
        sub_list = sub_list[i]
    sub_list[pos[-1]] = value
    return my_list

-- Puneeth


More information about the Tutor mailing list