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