Search code examples
pythonpython-3.xlisttuplespython-zip

merging each tuple with the next one in a list of tuples


I have a list of tuples which looks like this:

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

I would like to get:

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

I believe it's pretty simple, but I'm stuck unfortunately..

Any help would be really appreciated.


Solution

  • Here is one way with zip():

    >>> lst = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
    >>> [x + y for x, y in zip(lst, lst[1:])]
    [('a', 'b', 'c', 'd'), ('c', 'd', 'e', 'f'), ('e', 'f', 'g', 'h')]
    

    zip(lst, lst[1:]) zips each element with its next neighbour into a (x, y) tuple, then we add the tuples together with x + y.