Search code examples
pythonpython-3.xlistnested

How to update an element of an (arbitrarily) embedded list?


I am trying to update an element in an arbitrarily embedded list of lists.

For example, a potential embedded list looks like:

lst = ['a', ['b', ['c', 'd']]]

And I want to update 'b' to the string "NEWVALUE". We can assume every element is unique, and, if it helps, every list is of length 2.

I have attempted to change the value of 'b' by obtaining the index of this element as a list of integers, using the solution provided in: Index of an element in a nested list

So, I have a variable containing the index of the value to be changed, as a list of integers.

embedded_index = [1,0]

Ideally, I would want to update the element doing something like:

lst[embedded_index] = "NEWVALUE"

so that the updated lst is ['a', ['NEWVALUE', ['c', 'd']]]

But that obviously won't work Python doesn't access embedded indices using lists.

I have tried to update the value using the following code:

import copy
inner = copy.deepcopy(lst)
for i in embedded_index:
    inner = inner[i]

inner = "NEWVALUE"

But this does not update the original lst.

I do not necessarily need to use the embedded_index variable to update the value, this was the only way I could think of.


Solution

  • First, you deepcopy the original list. This means any changes made to inner won't show up in the original list. Don't do that.

    Second, inner = "NEWVALUE" doesn't update the original list because at this point inner is a string, and you're simply reassigning the name to a different value. Instead, you want to drill down to the last-but-one element of embedded_index (which makes inner a list) and then use the last element to index into that list and set the value:

    inner = lst # Do not deepcopy
    for i in embedded_index[:-1]: # iterate up to second-last embedded_index
        inner = inner[i]
    
    inner[embedded_index[-1]] = "NEWVALUE" 
    

    At the end of this code, lst becomes:

    ['a', ['NEWVALUE', ['c', 'd']]]
    

    You might find it helpful to read Python Names and Values by Ned Batchelder