1

I created a 2 d list with specified dimensions. Then I put numbers one by one into list cell. The values were correct in loop,but the list can not print correctly after loop. Someone can explain why? The code is here:

dist_list = [[1,5,9,40,8],[95,77,34,50,60]]
rows = 2 ##len(dist_list)

cols = len(dist_list[1]) 
sort_list = [[0]*cols]*rows
tempo = sorted(dist_list[1])
for i in range(cols):
    index = dist_list[1].index(tempo[i])
    sort_list[0][i] = dist_list[0][index]
    print (sort_list[0][i]) ## values are correct
    sort_list[1][i] = dist_list[1][index]
    print (sort_list[0][i]) ## values are correct
print(dist_list)
print(sort_list[0]) # problem is here. changed strangely
print(sort_list[1])

what I print like this: enter image description here

SeaHippo
  • 11
  • 2
  • There's only one inner list in `sort_list`, referenced `rows` times. To fix it, use `sort_list = [[0]*cols for i in range(rows)]`. See the linked question for further details. – PM 2Ring May 10 '18 at 04:00

0 Answers0