0

I created a 2D list in python as follows:

b = [[0] * 3] * 3 # 3 * 3

Now if I want to make the first element of the first row to be 1, I am doing this:

b[0][0] = 1

But if I print b, it is making the first element of every row to be 1, something like this:

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

What is the problem with my approach? Please suggest some alternatives to create a 2D list in python.

Nikhil Mishra
  • 1,182
  • 2
  • 18
  • 34
  • Some good detail here: https://stackoverflow.com/q/17702937/7954504 – Brad Solomon Mar 18 '18 at 15:28
  • You are creating multiple references to same list. One alternative to create a 2D list will be with copy : `b = [([0]*3).copy() for i in range(0,3)]` . – kanatti Mar 18 '18 at 15:43

0 Answers0