0

I have a list new_l_2 = [['0', '0', '10'], ['0', '2', '30'], ['1', '1', '20']]

and a list of lists matrix = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]

and when I execute

for i in new_l_2:
    matrix[int(i[0])][int(i[1])] = i[2]

I get [['10', '20', '30'], ['10', '20', '30'], ['10', '20', '30']]

but my wanted output is [[10.0, 0.0, 30.0], [0.0, 20.0, 0.0], [0.0, 0.0, 0.0]] where the first element of the first sublist of new_l_2 is the sublist of matrix wanted and the second element of the first sublist of new_l_2 is the position inside the sublist of matrix in which I put the third element of the first sublist of new_l_2. What am I missing here ?

matrix was created via

            matrix = []
            li = []
            for i in range(lignes):
                li.append(0.0)
            for i in range(colonnes):
                matrix.append(li)
Thibaultofc
  • 29
  • 10
  • Did you create `matrix` using something like this? `matrix = [0.0, 0.0, 0.0] * 3` – Daniel Geffen Dec 05 '20 at 14:43
  • Could you explain this more precisely ? – coderoftheday Dec 05 '20 at 14:44
  • 1
    You're adding the same list `li` to `matrix` multiple times. Do `matrix = [[0.0] * 3 for _ in range(colonnes)]` instead to make sure each sub-list is a new list. – Carcigenicate Dec 05 '20 at 14:45
  • I basically want to create a matrix (list of lists) where I put the numbers given in new_l_2 and the rest is zeros – Thibaultofc Dec 05 '20 at 14:46
  • I get the output ```[['10', 0.0, '30'], [0.0, '20', 0.0], [0.0, 0.0, 0.0]]``` when I print ```matrix```, isn't this want you want? – coderoftheday Dec 05 '20 at 14:46
  • With the modification given by Carcigenicate everything works as expected. Thanks! – Thibaultofc Dec 05 '20 at 14:48
  • 2
    See [here](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) for an explanation. It isn't exactly what you're doing here, but it's the same problem with the same fix. Daniel's initial comment hints at that. – Carcigenicate Dec 05 '20 at 14:49

1 Answers1

0

Your code is completely fine. I have checked the answer in colab. Just print the matrixenter image description here

Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25