8

beginner to python here.

I have 2 nested lists that I want to merge:

list1 = ['a',
         (b, c),
         (d, e),
         (f, g, h) ]

list2 = [(p,q),
         (r, s),
         (t),
         (u, v, w) ]

the output I am looking for is:

list3 = [(a, p, q),
         (b, c, r, s),
         (d, e, t),
         (f, g, h, u, v, w) ]

Can this be done without any external libraries? note: len(list1) = len(list2)

4
  • 3
    beginner to python here. - This means you should read the tutorial. Commented Oct 18, 2011 at 11:31
  • 1
    Hi. I have read the tuts. I know how to merge simple lists. But don't know how to go about with nested lists. Commented Oct 18, 2011 at 11:34
  • Also, the first element of list1 is a string in your example, but after the merge it seems to be an object. Commented Oct 18, 2011 at 11:34
  • ... which is valid if a == 'a', but then the rest doesn't make any sense. (t) is not a tuple, btw. -1. Commented Oct 18, 2011 at 11:35

4 Answers 4

19

Use the power of the zip function and list comprehensions:

list1 = [('a', ),
        ('b', 'c'),
        ('d', 'e'),
        ('f', 'g', 'h') ]

list2 = [('p', 'q'),
        ('r', 's'),
        ('t', ),
        ('u', 'v', 'w') ]

print [a + b for a, b in zip(list1, list2)]
Sign up to request clarification or add additional context in comments.

Comments

4
from operator import add
list3 = map(add, list1, list2)

1 Comment

Or, if you want to avoid the import, map(tuple.__add__, ...). (+1 for not insisting on list comprehensions where map() is more readable.)
0

If the order within an inner list/tuple is not important, you can use the mathematical set operations.

print [tuple(set(a)|set(b)) for a,b in zip(x,y)]

The set(a)|set(b) converts the iterables a and b to sets and takes the union of the two sets. They are then converted back to tuple as desired in the output format.

As you are a beginner to python, it is strongly recommended to master list comprehensions. It is way too powerful and concise. In addition to making your code more 'pythonic', list comprehensions can act as a friendlier replacement to 'map' and 'filter' functions.

Comments

0

Easy One

list_3 = []
list_3.extend(list_1 + list_2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.