0

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]]
1
  • Why do you want a list comprehension? Do you want new list objects or do you want to insert into the existing ones? What do you mean with "it does not work" when talking about the larger list? You also say you "end up with the right answer", so which is it? Do you get the right result or not? How large is your outer list and how large are your inner lists? Commented Sep 4, 2022 at 21:31

2 Answers 2

3

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]]
Sign up to request clarification or add additional context in comments.

7 Comments

Even much more inefficient than the already inefficient insert, though.
@KellyBundy If you want to insert to a list at first position, it will be always inefficient (O(n))
@KellyBundy The question is named "How to insert first element into list of lists using list comprehension" so I showed how it's done using list-comprehension.
They also ask "What is the right way to do this?", though, and I see no indication that they want new lists (they say "end up with the right answer") so I don't think this is the right way. Oh well, they already made up their mind...
@KellyBundy Please post a new answer here what you think is right way to do it. I'll upvote it :) It's always good to see alternatives.
|
3

This will also do the trick.

lol = [[0] + l for l in lol]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.