TAGS :Viewed: 14 - Published at: a few seconds ago

[ Appending first value of a list into the first value of another list; python ]

Working in python 2.7.

I have two lists (simplified to make explanations clearer).

T = [[1,0], [1,0], [0,5], [3, -1]]
B = [[1], [3], [2], [2]]

I would like to append the second list (B) so that the first value of the B list is appended to the first list in the T list and so on.

Ex- I want the output to look like:

T = [[1, 0, 1], [1, 0, 3], [0, 5, 2], [3, -1, 2]]

I've tried playing around with different types of append functions, but I haven't found anything that works. Knowing python, I'm sure there's a way.

Answer 1


map(list.extend, T, B)

or, if you prefer an explicit loop

for t, b in zip(T, B):
    t.extend(b)

Answer 2


Use zip

>>> t = [[1,0], [1,0], [0,5], [3, -1]]
... b = [[1], [3], [2], [2]]
>>> [x + y for x, y in zip(t, b)]
3: [[1, 0, 1], [1, 0, 3], [0, 5, 2], [3, -1, 2]]