Ad

Adding Elements From A List In A Nested List - Python

- 1 answer

I am using Python 3.6 and Django 1.11. I have a nested list -

nestedList = [[a, b, c], [d, e, f], [g, h, i]]

and another list -

newList = [1,2,3]

I need to club these and want a final list -

finalList = [[a, b, c, 1], [d, e, f, 2], [g, h, i, 3]]

Please let me know how this can be done.

Ad

Answer

just zip both lists together and create a new sublist:

nestedlist = [[1,2,3],[4,5,6],[7,8,9]]
newlist = [10,11,12]

result = [a+[x] for a,x in zip(nestedlist,newlist)]

print(result)

result:

[[1, 2, 3, 10], [4, 5, 6, 11], [7, 8, 9, 12]]
Ad
source: stackoverflow.com
Ad