0

I have to loop through the given list and modify its elements.

list1 = [[0, 0, 0, 0]] * 10
for i in range(len(list1)):
    for j in range(0, 10):
        list1[i][1] = j
print(list1)

#output:[[0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0], [0, 9, 0, 0]]

#But I want the output to be: [[0, 0, 0, 0], [0, 1, 0, 0], [0, 2, 0, 0], [0, 3, 0, 0], [0, 4, 0, 0], [0, 5, 0, 0], [0, 6, 0, 0], [0, 7, 0, 0], [0, 8, 0, 0], [0, 9, 0, 0]]

I need to understand why my code giving a different output. It would be helpful if you can explain to me why is it so.

Sahas
  • 259
  • 2
  • 12
  • `list1[i][1] = j` shouldn't be `list1[j][1] = j` ? Beside, you don't need to iterate 2 times if you want to change only 1 position of specified sublist - the second `for` with such change would be enough. – Shan Aug 07 '18 at 14:15
  • Also, you may want to have a look at [this thread](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly). – palivek Aug 07 '18 at 14:19
  • 2
    I tried list1[j][i] = j but the output comes to be the same – Sahas Aug 07 '18 at 14:24

1 Answers1

1

This should work:

In [21]: [[0, i, 0, 0] for i in range(10)]
Out[21]: 
[[0, 0, 0, 0],
 [0, 1, 0, 0],
 [0, 2, 0, 0],
 [0, 3, 0, 0],
 [0, 4, 0, 0],
 [0, 5, 0, 0],
 [0, 6, 0, 0],
 [0, 7, 0, 0],
 [0, 8, 0, 0],
 [0, 9, 0, 0]]

...or here's a more verbose version:

result = []
for i in range(10):
    result.append([0, i, 0, 0])
print(result)
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25