Search code examples
pythonstringlistzipconcatenation

Concatenation of elements in type zip in Python


In Python, I received a type zip like this as input:

[
    ('ef', ['c', 'b', 'a']),
    ('a', ['b']),
    ('ab', ['c']),
    ('b', ['c']),
    ('c', ['c', 'a']),
]

I have to concatenate the elements in the same item and create a new list of strings. The expected output is:

['efc', 'efb', 'efa', 'ab', 'abc', 'bc', 'cc', 'ca']

Note that the first element generates three different strings and the last one generates two strings. The problem is these items, because it has more than one element to concatenate. I tried using the join command but it is not working. Any help would be appreciated.


Solution

  • Use a nested comprehension:

    >>> zipped = [
        ('ef', ['c', 'b', 'a']),
        ('a', ['b']),
        ('ab', ['c']),
        ('b', ['c']),
        ('c', ['c', 'a']),
    ]
    >>> [pre + s for pre, suf in zipped for s in suf]
    ['efc', 'efb', 'efa', 'ab', 'abc', 'bc', 'cc', 'ca']
    

    If the comprehension doesn't make sense on first glance, think about it like a nested for loop:

    >>> for pre, suf in zipped:
    ...     for s in suf:
    ...         print(pre + s)
    ... 
    efc
    efb
    efa
    ab
    abc
    bc
    cc
    ca