I have a very specific problem where I need to know how to swap elements in a list or tuple.
I have one list that is called board state and I know the elements that need to be swapped. How do I swap them? In java with two-dimensional arrays, I could easily do the standard swap technique but here it says tuple assignment is not possible.
Here is my code:
board_state = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
new = [1, 1] # [row, column] The '4' element here needs to be swapped with original
original = [2, 1] # [row, column] The '7' element here needs to be swapped with new
Result should be:
board_state = [(0, 1, 2), (3, 7, 5), (6, 4, 8)]
How do I swap?
Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple.
Lists are mutable, so convert your
board_stateto alistoflists:And then use the standard Python idiom for swapping two elements in a list: