1

I am trying to replace elements in a 2d list. e-g I have this list

[['0', '0', '0'],
 ['0', '0', '0'], 
 ['0', '0', '0']]

and I want to convert first row to 1,1,1

here is what I have tried

l = [["0"]*3]*3

for i in range(3):
  l[0][i] = "1"

but I am getting the following output instead

[['1', '1', '1'],
 ['1', '1', '1'], 
 ['1', '1', '1']]

why is it converting all the rows to 1s?

I also tried to insert one element like this

l[1][1] = 1

and this coverts the [1] element of every row to 1 like this

[['0', 1, '0'], 
 ['0', 1, '0'], 
 ['0', 1, '0']]

Am I making a silly mistake or my interpreter has issues?

JaySabir
  • 322
  • 1
  • 10
  • It's not a silly mistake so much as a _common_ one, and no, nothing is wrong with your interpreter. – Chris Aug 30 '22 at 06:18
  • Just to add to the answers below: You can use the `id` function to get a number that identifies an object. Applying that to your matrix, you could observe that it contains three references to the same object. – Ulrich Eckhardt Aug 30 '22 at 06:29

3 Answers3

1

Because of the multiplication, the inner lists are all the same object. This is basically the same as:

inner = ["0"] * 3
outer = [inner, inner, inner]

When you now change inner, (or one element of outer), you change all references of it.

If you want to generate a 2D list with independent elements, i suggest list comprehension:

[["0" for i in range(3)] for j in range (3)]
Jeanot Zubler
  • 979
  • 2
  • 18
0

Your interpreter is not the issue. I think you are just constructing your matrix incorrectly. You can just change the first row of the matrix as such

matrix = [['0'] * 3 for _ in range(3)


for i in range(3):
    matrix[0][i] = '1'
mj_codec
  • 170
  • 8
0

Use

l = [ [0]*3 for i in range(3)]

In your code they all point to the same object.

Arash
  • 148
  • 1
  • 9