How to I append elements to a list of lists in python

Question:

I’ve a list of lists like:

a = [[1,2], [3,4]]

To each of the lists I want to add an element like 0 at the beginning, so that the result looks like:

b = [[0,1,2], [0,3,4]]

What’s the Python way to do it? I already tried it with "map", but without success.
I know, I could easily do it with a loop, but what’s the functional way?

Asked By: maybettle

||

Answers:

Use list comprehension and addition of lists to get in done in one short line of code:

b = [[0]+item for item in a]
Answered By: Claudio
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.