Search code examples
pythonlistloopsnested-loopsnested-lists

Looping through list and changing list values


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.


Solution

  • 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)