Search code examples
pythonpython-3.xlistlist-comprehensionpython-zip

Combine two lists alternatively


I am doing a simple list comprehension: combine two lists in alternative order and make another list.

big_list = [i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]

Expected output:

['2022-01-01','2022-01-31','2022-02-01','2022-02-28']

Present output:

Cell In[35], line 1
    [i,j for i,j in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])]
     ^
SyntaxError: did you forget parentheses around the comprehension target?

Solution

  • Do a nested comprehension to pull the items out of the zipped tuples:

    big_list = [
        i
        for t in zip(
            ['2022-01-01','2022-02-01'],
            ['2022-01-31','2022-02-28']
        )
        for i in t
    ]