[Tutor] Recursive assignment in nested lists

Alonzo Quijote alonzo.quijote at gmail.com
Sat Aug 4 21:44:11 CEST 2012


Thanks for all the help with this. I have 2 very quick follow-up questions:
---
1. Several responses proposed code like this:

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

There must be a good reason that the responders use a tmp variable like this?
But I notice that the same effects can be obtained with:

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

Is there something wrong with this latter approach?
---
2. Another response observes that the function can be defined recursively like this:

def setValueAtPosition3(list, pos, value):
    if len(pos) == 1:
        list[pos[0]] = value
    else:
        inner_list = list[pos[0]]
        new_pos = pos[1:]
        setValueAtPosition3(inner_list, new_pos, value)

Are the non-recursive solutions better? 
---
Thanks very much again, in advance, 
Alonzo

On Aug 4, 2012, at 12:43 AM, Peter Otten <__peter__ at web.de> wrote:

> 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
>> 
>> 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
>> 
>> For example
>>>>> aa=[1,2,[3,4]]
>> 
>>>>> setValueAtPosition(aa,[2,0],5)
>> [1, 2, [5, 4]]
>> 
>>>>> 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]

> 
> You have been shown working solutions, but for the learning experience it 
> will be instructive to try and come up with a recursive solution. Here's a 
> sketch:
> 
> def setValueAtPosition(list, pos, value):
>    if len(pos) == 1:
>        list[pos[0]] = value
>    else:
>        inner_list = ...
>        new_pos = ...
>        setValueAtPosition(inner_list, new_pos, value)
> 
> Can you fill in the blanks?
> 



More information about the Tutor mailing list