4

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 Answers2

5

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)))
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
2

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.

jkr
  • 17,119
  • 2
  • 42
  • 68
  • but those are two for loops, I think this is not as clean, but might be faster ` xx = [] , _ = [xx.extend([x,y]) for x, y in zip(a,b)] ` now xx is ` [1, 'a', 2, 'b', 3, 'c', 4, 'd'] ` – Jose Angel Sanchez May 21 '20 at 21:22
  • Maybe, but I would choose clean code over fast code. *Premature optimization is the root of all evil* – jkr May 21 '20 at 21:27