[Tutor] Recursive assignment in nested lists

Steven D'Aprano steve at pearwood.info
Sat Aug 4 09:27:54 CEST 2012


On 04/08/12 16:58, Alonzo Quijote 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


Yes it is possible, but if you need this, you should strongly consider 
rearranging your data so it is easier to work with.

But, for what it's worth, try this:


def setValueAtPosition(list, pos, value):
     tmp = list
     for i in pos[:-1]:
         tmp = tmp[i]
     tmp[pos[-1]] = value


There's no need to return the list argument, because it changes it in-place.

And here is your example:


py> aa=[1, 2, [3, 4]]
py> setValueAtPosition(aa, [2, 0], 5)
py> aa
[1, 2, [5, 4]]


And a more complicated example:

py> L = [0, 1, 2, [3, 4, [5, 6, [7, [8, 9, 10], 11], 12], 13, 14], 15]
py> setValueAtPosition(L, [3, 2, 2, 1, 0], "Surprise!")
py> L
[0, 1, 2, [3, 4, [5, 6, [7, ['Surprise!', 9, 10], 11], 12], 13, 14], 15]



But really, don't do this. Such a thing is hard to understand, hard to use, 
hard to maintain, and hard to debug when you have a problem. Try to avoid 
having deeply nested lists like that, your life will be much simpler.



-- 
Steven


More information about the Tutor mailing list