Adding data to a nested list in Python

I have a nested list, for example:

nlist = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] 

Before inserting this list into the database, I would like to add a “column” to it with the same value in each row of the new column, for example:

 nlist = [ [a, 1, 2, 3], [a, 4, 5, 6], [a, 7, 8, 9], ] 

What is the best way to do this when, for example, the original nested list can contain hundreds of lines?

+4
source share
3 answers

Why not change the original list (if that's all you want to do):

 for row in nlist: row.insert(0, a) 
+7
source

If you want to create a new list, this will also work ...

 nlistnew = [[a]+row for row in nlist] 

EDIT: Fixed code according to Felix Kling's comment. Thanks!

+2
source

Iterate over the external list. For each method, use the list of internal lists insert(0, new_data) .

0
source

Source: https://habr.com/ru/post/1343476/


All Articles