1

I use this to create 4x4 matrix of 'x':

listof=[] #table
nic=[] #row
max = 4 #tabele size
nic = ['x']*max #row of x-es
listof = [nic]*max #table of rows
print(listof) #it looks ok
listof[1][1] ="o" #changing one x to o
print(listof) # wrong since all rows have o on index 1

?how come?

BTW: I know it Works if I use:

listof = [["x" for x in range(max)] for y in range(max)]

But what is wrong with the code above? Thanks

overlord
  • 13
  • 2

1 Answers1

1

The problem is that listof ends up consisting of four references to the same list. As a result, when you change an element in one row, it changes in all rows.

NPE
  • 486,780
  • 108
  • 951
  • 1,012