Merge sliced lists

list, python

Solution

You can use the `zip()` function to join them back together:

>>> l0 = [1,4]; l1 = [4,10]; l2 = [9,18]
>>> zip(l0, l1, l2)
[(1, 4, 9), (4, 10, 18)]
>>> [x for t in zip(l0, l1, l2) for x in t]
[1, 4, 9, 4, 10, 18]

Or use `itertools.chain`:

>>> from itertools import chain
>>> list(chain(*zip(l0, l1, l2)))
[1, 4, 9, 4, 10, 18]

In Python 3, where `zip` is a generator function, `itertools.chain.from_iterable` might be preferrable, as others have pointed out already.

Problem

I have a list with N elements, and I slice it using certain step, let's say 3: ``` slice0 = text[0::3] slice1 = text[1::3] slice2 = text[2::3] ``` After doing some processing separatedly, now I'd need to merge them back in the same positions they were in the original list. Is there a similar (easy) way to do this? Example: ``` L = [1,2,3,4,5,6] -> L0 = [1,4], L1 = [2,5], L2 = [3,6] ``` Then some processing (say multiply each list by 1, 2 and 3 respectively: ``` L0 = [1,4], L1 = [4,10], L2 = [9,18] ``` Merge them back to their original positions ``` L = [1,4,9,4,10,18] ``` Thank you.

Original source