There is a working code for specifying a two-dimensional array:

field=[] for i in range(8): block = [] for j in range(8): block.append('X') field.append(block) 

He doesn’t fade, but it works! The essence of the problem is that with "not beautiful" initialization, all the lists of individual objects and when we make a change in a cell, only it changes. How to reduce, so that the code is more "pythonistic", but also to preserve the correct cell variability (functionality)?

Sort of

 field = [['X']*8]*8 

But so when changing the field, all the fields in the coordinate change due to the fact that all refer to one list.
I want only field [2] [2] to change when field [2] [2] = 'O', and not the whole column

field[2][2] = 'O'

 ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] ['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X'] 

Tried to use [:], list, but no result

  • Well, just instead of self._field=[] leave _field=[] What is this self of you at all? - Igor Igoryanych
  • This is all in the classroom, but this is not the point I’ll self - remove everywhere, the code will not work from this) - orlovw
  • remove the field = [['X']*8]*8 and will only be changed in one place - Igor Igoryanych
  • or you field = [['X']*8]*8 with this line just tried to reduce the code? - Igor Igoryanych
  • @ IgorIgoryanych yes, it was her who cut down and tried - orlovw

1 answer 1

 L = [['X' for n in range(8)] for n in range(8)] 
  • Yes, this is it, thanks! - orlovw
  • And, I understood the problem: So it will be a bit easier: [['X']*8 for i in range(8)] - 0andriy