Interleave 4 lists of same length python [duplicate] Interleave 4 lists of same length python [duplicate] arrays arrays

Interleave 4 lists of same length python [duplicate]


Provided the lists are the same length, zip() can be used to interleave four lists just like it was used for interleaving two in the question you linked:

>>> l1 = ["a", "b", "c", "d"]>>> l2 = [1, 2, 3, 4]>>> l3 = ["w", "x", "y", "z"]>>> l4 = [5, 6, 7, 8]>>> l5 = [x for y in zip(l1, l2, l3, l4) for x in y]>>> l5['a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8]


itertools.chain and zip:

from itertools import chainl1 = ["a", "b", "c", "d"]l2 = [1, 2, 3, 4]l3 = ["w", "x", "y", "z"]l4 = [5, 6, 7, 8]print(list(chain(*zip(l1, l2, l3, l4))))

Or as @PatrickHaugh suggested use chain.from_iterable:

list(chain.from_iterable(zip(l1, l2, l3, l4)))


From itertools recipes

The itertool recipes suggest a solution called roundrobin that allows for lists of different lengths.

from itertools import cycle, islicedef roundrobin(*iterables):    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"    # Recipe credited to George Sakkis    num_active = len(iterables)    nexts = cycle(iter(it).__next__ for it in iterables)    while num_active:        try:            for next in nexts:                yield next()        except StopIteration:            # Remove the iterator we just exhausted from the cycle.            num_active -= 1            nexts = cycle(islice(nexts, num_active))print(*roundrobin(*lists)) # a 1 w 5 b 2 x 6 c 3 y 7 d 4 z 8

With slicing

Alternatively, here is a solution that relies solely on slicing, but requires that all lists be of equal lengths.

l1 = ["a","b","c","d"]l2 = [1,2,3,4]l3 = ["w","x","y","z"]l4 = [5,6,7,8]lists = [l1, l2, l3, l4]lst = [None for _ in range(sum(len(l) for l in lists))]for i, l in enumerate(lists):    lst[i:len(lists)*len(l):len(lists)] = lprint(lst) # ['a', 1, 'w', 5, 'b', 2, 'x', 6, 'c', 3, 'y', 7, 'd', 4, 'z', 8]