Search code examples
pythonfor-loopinsert

How to insert an element in each part of 2 level list?(python)


I have two-level list with 3 float element in each part of this list, it looks like that: [[0.0, 0.0, 0.0], [0.0, 5.0, 0.0], [2.53188872, 2.16784954, 9.49026489], [5.0, 0.0, 0.0]....] I need to insert a number at the beginning of each element of this list) so that it looks like this: [[1, 0.0, 0.0, 0.0], [2, 0.0, 5.0, 0.0], [3, 2.53188872, 2.16784954, 9.49026489], [4, 5.0, 0.0, 0.0]....]

I tried using a for loop:

for i in range(len(additional_nodes)): additional_nodes[i].insert(0, i+1) print(additional_nodes)

but i got something like this: [[31, 28, 25, 0, 0.0, 0.0, 0.0], [16, 12, 10, 4, 1, 0.0, 5.0, 0.0], [53, 50, 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2, 2.53188872, 2.16784954, 9.49026489]...] what's my problem?


Solution

  • I am not sure where it went wrong. Coz it works for me fine. If u are sure that it is not working and in immediate need of a solution, try reverting and appending and then reverting again. Lol

    l = [[0.0, 0.0, 0.0], [0.0, 5.0, 0.0], [2.53188872, 2.16784954, 9.49026489], [5.0, 0.0, 0.0]]
    for i in range(len(l)):
        l[i] = l[i][::-1]
        l[i].append(i+1)
        l[i] = l[i][::-1]
    print(l)