Python - Merge two lists of tuples into one

3821 views python
-5

I have two lists of tuples and i want to merge them into one Ex : List1 = [(a, 1),(b,2)] List2 =[(a, 3),(b,4)] I want theresult to be Result = [(a, 1,3),(b,2,4)]

answered question

tuples are immutable - you would have to reconstruct them. what did you try to solve it?

Do you mean a tuple starts with a should match another tuple that starts with a? Do they always appear at same order in the two lists.

1 Answer

13

>>> a = 1
>>> b = 3
>>> l1 = [(a, 1),(b,2)]
>>> l2 = [(a, 3),(b,4)]
>>> result = []
>>> for i1,i2 in zip(l1,l2):
    result.append(tuple([i1[0]])+tuple(i1[1:])+tuple(i2[1:]))

>>> result
[(1, 1, 3), (3, 2, 4)]
>>> 

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories