Reputation: 1402
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?
Upvotes: 3
Views: 12701
Reputation: 141790
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_state
to a list
of list
s:
>>> board_state = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
And then use the standard Python idiom for swapping two elements in a list:
>>> board_state[1][1], board_state[2][1] = board_state[2][1], board_state[1][1]
>>> board_state
[[0, 1, 2], [3, 7, 5], [6, 4, 8]]
Upvotes: 5