unicornication
unicornication

Reputation: 627

Python list of lists behaving strange

This is likely a duplicate question but it is different in that the error occurs when I am using for loops. To explain, if I have list:

x = [[1,2,3],[1,2,3],[1,2,3]]

and I do

x[0][0] = 5

The list will change to

[[5,2,3],[5,2,3],[5,2,3]]

A comment pointed out the above may be incorrect, below is output directly from the console:

>>> x = Board()
>>> x.create(6,6)
[['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', '']]
>>> x.board
[['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', ''], ['', '', '', '', '', '']]
>>> x.board[0][1]
''
>>> x.board[0][1] = 1
>>> x.board
[['', 1, '', '', '', ''], ['', 1, '', '', '', ''], ['', 1, '', '', '', ''], ['', 1, '', '', '', ''], ['', 1, '', '', '', ''], ['', 1, '', '', '', '']]
>>> 

The solution described in other answers involve creating a for loop to create a new list element, however I'm not sure how to implement that in my code, shown below-

class Board():
   def create(self, rows, cols):
        self.board = []
        col_template = []
        for col in range(cols):
                col_template.append("")
        for row in range(rows):
            self.board.append(col_template)
        return self.board

Where rows, cols are some even integers

Upvotes: 1

Views: 69

Answers (1)

Marcin
Marcin

Reputation: 238111

I think you need to do this:

  self.board.append(col_template[:])

Otherwise, your board will have references to the same array.

Your correct example should be:

a=[1,2,3]
x = [a,a,a]
x[0][0] = 5
print(x) # [[5, 2, 3], [5, 2, 3], [5, 2, 3]]

To fix the above problem:

a=[1,2,3]
x = [a[:],a[:],a[:]]
x[0][0] = 5
print(x) # [[5, 2, 3], [1, 2, 3], [1, 2, 3]]

This happens because x stores only references to the same list a. You need explicitly create copies (done by a[:]) of a to have different sublists in x.

Upvotes: 4

Related Questions