[[+content_image]]
K
K
Kryptonit2021-11-21 18:29:22
Python
Kryptonit, 2021-11-21 18:29:22

Incorrect padding of a 2D Python list?

I declare a dynamic list M*N, let M =2, N =2
Elements = [[0]*M]*N
I need to put a certain value in place of a certain element, but the element is also entered dynamically, so I can iterate through for:
for i in range(M):
for j in range(N):
if i == 0 and j == 0:
Elements[i][j] = 1000
print(Elements)
I expect it to print [[1000,0] , [0,0]]
A-n no [[1000,0],[1000,0]]

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
S
soremix, 2021-11-21
@Kryptonit

You created the list a bit wrong. When multiplying, you did not get a new list, but a link to the first one. Changed the first list - changed the second. Can be checked viaid()

Elements = [[0]*M]*N
print(id(Elements[0]) == id(Elements[1]))

The correct option would be something like this:
Elements = [[0]*M for i in range(N)]
print(id(Elements[0]) == id(Elements[1]))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question