1

I have created a 10 by 10 game board. It is a 2D list, with another list of 2 inside. I used board = [[['O', 'O']] * 10 for x in range(1, 11)]. So it will produce something like

['O', 'O'] ['O', 'O']...

['O', 'O'] ['O', 'O']...

Later on I want to set a single cell to have 'C' I use board.gameBoard[animal.y][animal.x][0] = 'C' board being the class the gameBoard is in, and animal is a game piece, x & y are just ints. Some times it will work and the specified cell will become ['C', 'O'], other times it will fill the entire row with ['C', 'O']['C', 'O']['C', 'O']['C', 'O'] Does anyone know why that might be happening?

EasilyBaffled
  • 3,822
  • 10
  • 50
  • 87
  • related: [Multiply operator applied to list(data structure)](http://stackoverflow.com/questions/974931/multiply-operator-applied-to-listdata-structure) – jfs Feb 23 '13 at 03:28

3 Answers3

4

Basically, you're creating a whole bunch of references to the same list -- To demonstrate, consider:

[ [] ]*10

If you print the ids:

>>> print map(id,[ [] ]*10)
[958336, 958336, 958336, 958336, 958336, 958336, 958336, 958336, 958336, 958336]

you'll see they're all the same:

The easiest fix is to do something like:

[ [['O','O'] for _ in range(10)] for x in range(1, 11) ]
mgilson
  • 300,191
  • 65
  • 633
  • 696
3

Don't worry, a lot of people have fallen into the same trap as you.

[['O', 'O']] * 10 creates 10 copies of the same list. That means that when you change an element in one of the lists, the change is reflected in all the others.

Do this instead to create 10 separate lists:

[[['O', 'O'] for j in range(10)] for i in range(10)]  # or xrange in Python 2
Community
  • 1
  • 1
Volatility
  • 31,232
  • 10
  • 80
  • 89
0

Your board is getting multiple references to the same array. You need to replace the * 10 with another list comprehension.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175