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

Question:

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?

Answers:

Try this, you have an error in your loop:

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

Or if you want , better enumerate:

for i, lst in enumerate(additional_nodes, start=1):
    lst.insert(0, i)
Answered By: Raziak

Best to use enumerate like this:

mlist = [[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, e in enumerate(mlist, 1):
    e.insert(0, i)

print(mlist)

Output:

[[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]]
Answered By: Fred

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)
Answered By: Tiger God

You can try as below by loop over multi lists

Code:

ls = [[0.0, 0.0, 0.0], [0.0, 5.0, 0.0], [2.53188872, 2.16784954, 9.49026489], [5.0, 0.0, 0.0]]

[[idx, *val] for idx,val in enumerate(ls)]

Output:

[[0, 0.0, 0.0, 0.0],
 [1, 0.0, 5.0, 0.0],
 [2, 2.53188872, 2.16784954, 9.49026489],
 [3, 5.0, 0.0, 0.0]]
Answered By: R. Baraiya
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.