python: flat zip

Viewed 1183

I have

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd']

where a has one more element. zip(a,b) returns [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]. However, I want

[1, 'a', 2, 'b', 3, 'c', 4, 'd']

What is the most elegant way?

2 Answers

itertools has a function for this.

from itertools import chain

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd']
result = list(chain.from_iterable(zip(a, b)))

Using list comprehensions, one can use the following:

a = [1, 2, 3, 4, 5]
b = ['a', 'b', 'c', 'd']
result = [item for sublist in zip(a, b) for item in sublist]
# result is [1, 'a', 2, 'b', 3, 'c', 4, 'd']

This uses the list-flattening comprehension in https://stackoverflow.com/a/952952/5666087.

Related