I have tried to make a program in python that replaces an item in an arbitrarily nested list. To get to the item, the program would use a list of indexes like [3, 0, 1]
. It would be similar to traditional way of accessing nested lists like list[3][0][1]
.
I have a function that is supposed to replace an item in a nested list.
def ReplaceItemInNestedList(nestedList, indexList, replacement):
for i in indexList[:-1]:
nestedList = nestedList[i]
lastIndex = indexList[-1]
nestedList[lastIndex] = replacement
And it perfectly works when used like that. Only problem is that I don't understand why that is:
myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6
ReplaceItemInNestedList(myNestedList, myIndexList, replacement)
myNestedList: [[0, 1], [6, 3]]
I don't understand how is myNestedList
still a nested list instead of a regular one. I'd expect more specifically it to be the one where an item will get replaced. That'd be because nestedList would repeatedly get redefined while the for-loop is running and get redefined from a nested list to the regular list inside it.
When I put the function inside my code I get the behaviour I understand but it's not what I want.
myNestedList = [[0, 1], [2, 3]]
myIndexList = [1, 0]
replacement = 6
for i in myIndexList[:-1]:
myNestedList = myNestedList[i]
lastIndex = myIndexList[-1]
myNestedList[lastIndex] = replacement
myNestedList: [6, 3]
Ideally I'd like there to be a class NestedList
with a self.value = [[0, 1], [2, 3]]
parameter which would change when called method changeValueAtIndexList(indexList, replacement)
, but I really can't seem to be able to put the current "magical" solution into a class. Please help me understand what is going on with my program.