Reputation: 143
I was writing a program that needs a 2d array, and came upon a strange problem.
At first, I wrote:
board = [[]]*11
to make eleven arrays within an array.
Then I wanted eleven blanks within each array so I wrote:
for i in range(11):
board[i].append(' ')
I wanted to fill the third array, from index 4 to 7 with stars, so I wrote:
for i in range(4, 7):
board[2][i] = '*'
But then unexpectedly, instead of only the third array being affected by the code, all of the arrays in the "board" were changed.
So of course, I wrote:
board2 = []
for i in range(11):
board2.append([])
to create my array, and then wrote:
for i in range(11):
for i in range(11):
board2[i].append(' ')
to create my array with 11 arrays containing 11 blanks.
After I created my array like that, I was able to run the code to add the stars, and as expected, only affected one array instead of all of them.
Could anybody please explain what are the difference between the two seemingly similar arrays?
Upvotes: 2
Views: 191
Reputation: 838256
The list [[]] * 11
contains 11 references to the same list.
Your second example creates 11 different lists.
board = [[]]*11
# ^^ this is called just once
board2 = []
for i in range(11):
board2.append([])
# ^^ this is called 11 times, creating 11 different lists
Another way to write the second example is to use a list comprehension:
[[] for i in range(11)]
Upvotes: 7