Pythonic way to mix two lists

IMHO the best way is:

result = [item for sublist in zip(a,b) for item in sublist]

It's also faster than sum and reduce ways.

UPD Sorry missed that your second list is bigger by one element :) There is another crazy way:

result = [item for sublist in map(None, a, b) for item in sublist][:-1]

>>> long = [1, 3, 5, 7]
>>> short = [2, 4, 6]
>>> mixed = []
>>> for i in range(len(long)):
>>>     mixed.append(long[i])
>>>     if i < len(short)
>>>         mixed.append(short[i])
>>> mixed
[1, 2, 3, 4, 5, 6, 7]

mixing two lists is a job for zip:

res = []
for a,b in zip(list_long, list_short):
    res += [a,b]

for lists of differing lengths, define your own function:

def mix(list_long, list_short):
    result = []
    i,j = iter(list_long), iter(list_short)
    for a,b in zip(i,j):
        res += [a,b]
    for rest in i:
        result += rest
    for rest in j:
        result += rest
    return result

using the answer given by Mihail, we can shorten this to:

def mix(list_long, list_short):
    i,j = iter(list_long), iter(list_short)
    result = [item for sublist in zip(i,j) for item in sublist]
    result += [item for item in i]
    result += [item for item in j]
    return result

>>> import itertools
>>> a
['1', '2', '3', '4', '5', '6']
>>> b
['a', 'b', 'c', 'd', 'e', 'f']
>>> list(itertools.chain.from_iterable(zip(a,b)))
['1', 'a', '2', 'b', '3', 'c', '4', 'd', '5', 'e', '6', 'f']

zip() produces a iterable with the length of shortest argument. You can either append a[-1] to the result, or use itertools.zip_longest(izip_longest for Python 2.x) with a fill value and delete that value afterwards.

And you can use more than two input sequences with this solution.

For not appending the last value, you can try this dirty approach, but I don't really recommend it, it isn't clear:

>>> a
[1, 2, 3, 4, 5]
>>> b
['a', 'b', 'c', 'd', 'e', 'f']
>>> [a[i//2] if i%2 else b[i//2] for i in range(len(a)*2+1)]
['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f']

(For Python 2.x, use single /)

Tags:

Python