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?

Dmitry B.
  • 8,763
  • 3
  • 39
  • 59
tabchas
  • 1,344
  • 2
  • 17
  • 36

1 Answers1

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]]
Community
  • 1
  • 1
johnsyweb
  • 129,524
  • 23
  • 177
  • 239