0

I don't understand why I am assigning to the first element in every list below:

➜  ~  python
Python 2.7.3 (default, Sep 26 2012, 21:53:58) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> board = [[None]*5]*5
>>> print board
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
>>> board[0][0] = 1
>>> print board
[[1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None]]

I would expect the final output to be this:

[[1, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
Ayush
  • 41,754
  • 51
  • 164
  • 239

1 Answers1

1

Your code is equivalent to this one:

x = [None]*5
board = [x for i in range(5)]

If you want 5 different lists, do it:

board = [[None]*5 for i in range(5)]
iurisilvio
  • 4,868
  • 1
  • 30
  • 36