3

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?

Friedrich
  • 1,739
  • 1
  • 9
  • 24
  • I use now `sum(zip(a, b), ())`. It returns a flat tuple. It is a modification of this controverse [answer](https://stackoverflow.com/a/952946/11769765). – Friedrich May 21 '20 at 21:42
  • Mapping the `+` operator to all elements, I come across [reduce](https://book.pythontips.com/en/latest/map_filter.html#reduce), thus `reduce(lambda x,y: x+y, zip(a,b))`. But this is also given in https://stackoverflow.com/a/952943/11769765. – Friedrich Jun 07 '20 at 13:49
  • Another duplicate: [Python: Intertwining two lists](https://stackoverflow.com/q/6356041/7851470). – Georgy Jun 19 '20 at 23:07

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
  • 48,602
  • 11
  • 68
  • 105
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.

jakub
  • 13,953
  • 2
  • 30
  • 52
  • 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* – jakub May 21 '20 at 21:27