0

I have mat = [[0]*5]*5 to create a 2-d matrix of all zeros. When I do mat[0][0] = 1, I want it to be only

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

but when I print mat, I get:

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

How do I access an individual element?

canonball
  • 515
  • 7
  • 22
  • You *are* accessing an individual element, however, your "2-d" matrix isn't a matrix at all, it is a *list*, that contains 5 other lists, which happen to be *equal by identity*. As the duplicate target shows, the solution is to create a list which contains 5 different lists. – juanpa.arrivillaga Oct 20 '17 at 18:16
  • even this does the same thing: mat = [[0 for i in range(5)] for j in range(5)] – canonball Oct 20 '17 at 18:23
  • No, it doesn't. I don't know what you are doing, there are several inconsistencies with the example input/output you've provided. But that list-comprehension definitely works. – juanpa.arrivillaga Oct 20 '17 at 18:28

0 Answers0