How to insert first element into list of lists using list comprehension

Question:

I have a list of lists and want to insert a value into the first position of each list. What is wrong with this code? Why does it return none data types at first, and then if I access the variable again, it shows up with data? I end up with the right answer here, but I have a much larger list of lists I am trying to this with, and it does not work. What is the right way to do this? Thanks.

lol = [[1,2,3],[1,2,3],[1,2,3]]
[lol[i].insert(0,0) for i in np.arange(0,3)]

The results:

lol = [[1,2,3],[1,2,3],[1,2,3]]
[lol[i].insert(0,0) for i in np.arange(0,3)]
Out[201]: [None, None, None]

lol
Out[202]: [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
Asked By: user8229029

||

Answers:

list.insert inserts the value in-place and always returns None. To add new value into a list with list comprehension you can do:

lol = [[0, *subl] for subl in lol]
print(lol)

Prints:

[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
Answered By: Andrej Kesely

This will also do the trick.

lol = [[0] + l for l in lol]
Answered By: shashank2806
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.