Search code examples
pythonlist-comprehension

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


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]]

Solution

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