I have a list with nested lists and I want to create a function (modify_list) that gets a tuple and modifies the passed pointer with a passed value argument. The problem is that I’m not sure how to modify a nested value like this programmatically by reference.
Simplified example:
l = [[1, [2,3, [4,5,6]]]]
If I call the function modify_list, these would be how to use it and the expected results:
> l[0][1][2][2]
6
> modify_list((0, 1, 2, 2), 8)
> l
[[1, [2,3, [4,5,8]]]]
> modify_list((0, 1, 1), 14)
> l
[[1, [2,14, [4,5,8]]]]
Thanks
You can determine each sublist by accessing it with the respective index. Use the last index to assign the value:
Note that this function operates on an arbitrary list (the first argument), and not only
l. If you want to always modifyl, usefunctools.partial:Note that nested lists, and accessing values by indicies, are often a sign of a bad data architecture. Have you considered a
dictwhose keys are tuples?