Home > Mobile >  Update a position in list of list Python
Update a position in list of list Python

Time:08-19

I have a list:

[[6, 8, 5, 1, 3, 2, 9, 4, 7],
[7, 3, 4, 5, 9, 8, 2, 1, 6],
[2, 1, 9, 7, 6, 4, 8, 5, 3],
[9, 2, 6, 8, 7, 1, 5, 3, 4],
[8, 5, 1, 3, 4, 9, 6, 7, 2],
[4, 7, 3, 2, 5, 6, 1, 8, 9],
[5, 6, 8, 4, 2, 7, 3, 9, 1], 
[3, 4, 2, 9, 1, 5, 7, 6, 8],
[1, 9, 7, 6, 8, 3, 4, 2, 5]]

I want to update a position in this list for example:

update_list(position: tuple[int, int], value: Optional[int])

where value is the element that is going to replace the original element in the list

Thus update_list((1, 1), 5) should replace 3 with 5

What is the best way to code for this?

CodePudding user response:

You can directly index into the inner list!

>>> content = [[6, 8, 5, 1, 3, 2, 9, 4, 7],
... [7, 3, 4, 5, 9, 8, 2, 1, 6],
... [2, 1, 9, 7, 6, 4, 8, 5, 3],
... [9, 2, 6, 8, 7, 1, 5, 3, 4],
... [8, 5, 1, 3, 4, 9, 6, 7, 2],
... [4, 7, 3, 2, 5, 6, 1, 8, 9],
... [5, 6, 8, 4, 2, 7, 3, 9, 1], 
... [3, 4, 2, 9, 1, 5, 7, 6, 8],
... [1, 9, 7, 6, 8, 3, 4, 2, 5]]
>>> content[1][1]
3
>>> content[1][1] = 5
>>> content[1][1]
5
>>> content
[[6, 8, 5, 1, 3, 2, 9, 4, 7], [7, 5, 4, 5, 9, 8, 2, 1, 6], [2, 1, 9, 7, 6, 4, 8, 5, 3], [9, 2, 6, 8, 7, 1, 5, 3, 4], [8, 5, 1, 3, 4, 9, 6, 7, 2], [4, 7, 3, 2, 5, 6, 1, 8, 9], [5, 6, 8, 4, 2, 7, 3, 9, 1], [3, 4, 2, 9, 1, 5, 7, 6, 8], [1, 9, 7, 6, 8, 3, 4, 2, 5]]

CodePudding user response:

This one works for me:

content = [[6, 8, 5],[1, 2, 3]]

def update_list(a, b):
    content[a[0]][a[1]] = b

update_list((0,0),25) #It replace the first element by 25

The Output of content:

[[25, 8, 5], [1, 2, 3]]
  • Related