0

I have previously worked in C, I am facing problem in assigning value in 2d list

graph = [[0]*3]*3
print(graph)
graph[0][1] = 3
print(graph)

Output

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 3, 0], [0, 3, 0], [0, 3, 0]]

Expected output :

[[0, 3, 0], [0, 0, 0], [0, 0, 0]]

Is there any way to assign values other than using numpy array as answered in Assigning values Python 2D Array

Amish
  • 197
  • 1
  • 11
  • 1
    It's a recurrent question. Try `graph = [[0 for _ in range(3)] for _ in range(3)]` instead when you make `graph`. – j1-lee Mar 02 '22 at 06:15
  • Yes, but I still can't understand how is it different from graph = [[0]*3]*3 – Amish Mar 02 '22 at 06:17

1 Answers1

2

you can use a for loop to do this simply

a = []
for i in range(3):
    a.append([0]*3)