4

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?

1 Answer 1

6

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 lists:

>>> 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]]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.