Search code examples
pythonlistmergetuples

Merging two tuple of tuples


I have two tuples a = (('1',), ('2',)) and b = (('3',), ('4',))

I need an output like

result = (('1','3',), ('2','4',))

I have tried converting the tuples into a list and used zip to merge into a single tuple tuple(zip(list(a), list(b))) and also tuple(zip(a,b)) which yields ((('1',), ('3',)), (('2',), ('4',))) as the result.

What should I be doing to get the desired result? I saw about immutability of tuples but I am getting the tuples from another service and I all I can do is to convert the obtained tuple to a list to get the expected output.


Solution

  • Zipping is the right approach, but you then have to flatten your paired tuples still; you could concatenate them:

    result = tuple(x + y for x, y in zip(a, b))
    

    Alternatively, flatten your a and b tuples before zipping:

    result = tuple(zip((v for t in a for v in t), (v for t in b for v in t)))
    

    Flattening can also be done with itertools.chain(), which is perhaps more readable:

    from itertools import chain
    
    result = tuple(zip(chain(*a), chain(*b)))
    

    Demo:

    >>> a = (('1',), ('2',))
    >>> b = (('3',), ('4',))
    >>> tuple(x + y for x, y in zip(a, b))
    (('1', '3'), ('2', '4'))
    >>> tuple(zip((v for t in a for v in t), (v for t in b for v in t)))
    (('1', '3'), ('2', '4'))
    >>> from itertools import chain
    >>> tuple(zip(chain(*a), chain(*b)))
    (('1', '3'), ('2', '4'))