Combine two lists alternatively

159 Views Asked by At

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?
5

There are 5 best solutions below

1
On BEST ANSWER

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
]
0
On

my code pairs corresponding elements from l1 and l2 using the zip function, and using for loop to combine each element with its pair

l1 = ["2022-01-01", "2022-02-01"]
l2 = ["2022-01-31", "2022-02-28"]
zipped_lists = zip(l1, l2)
l3 = []
for list in zipped_lists:
    for date in list:
        l3.append(date)
print(l3)
# l3 = ['2022-01-01', '2022-01-31', '2022-02-01', '2022-02-28']
0
On

You can unnest from zip:

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

#output

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

One way is to use itertools:

import itertools
big_list = list(itertools.chain(*zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])))

#output

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

Edit:

This will be very slow:

sum([list(x) for x in zip(['2022-01-01','2022-02-01'],['2022-01-31','2022-02-28'])],[])

#output

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

A zip-free comprehension: alternated append.

l1 = ['2022-01-01','2022-02-01']
l2 = ['2022-01-31','2022-02-28']

l = [l1[i//2] if not i % 2 else l2[(i)//2] for i in range(min(len(l1), len(l2))*2)]

The min is used to ensure equally sized lists (as zip would do).


A zip-free functional approach. If lists of different sizes then a zip-like "politics" is applied.

from itertools import chain
# l1, l2 from above

l = list(chain.from_iterable(map(lambda x, y: (x, y), l1, l2)))
10
On

Just for the sake of it, because I'd actually use zip too:

list1 = ['2022-01-01','2022-02-01']
list2 = ['2022-01-31','2022-02-28']
big_list = [(list1, list2)[i%2][i//2] for i in range(2 * min(len(list1), len(list2)))]

Another version, using itertools.cycle to switch between 2 iterators over the two lists:

from itertools import cycle
big_list = [next(next(cy)) for cy in [cycle((iter(list1), iter(list2)))] for _ in range(2 * min(len(list1), len(list2)))]