0

Hi I have three lists like such:

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

How can I make a new list such that it takes values from all list. For example, it's first three elements will be 1,2,3 as they are the first elements of a,b,c. Therefore, it would look something like

d = [1,2,3,2,3,4,3,4,5,4,5,6]
NoLand'sMan
  • 534
  • 1
  • 3
  • 17

4 Answers4

7

You can do that using zip:

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

[item for sublist in zip(a, b, c) for item in sublist]
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]

The first for loop:

for sublist in zip(a, b, c)

will iterate on tuples provided by zip, which will be:

(1st item of a, 1st item of b, 1st item of c)
(2nd item of a, 2nd item of b, 2nd item of c)
...

and the second for loop:

for item in sublist

will iterate on each item of these tuples, building the final list with:

[1st item of a, 1st item of b, 1st item of c, 2nd item of a, 2nd item of b, 2nd item of c ...]

To answer @bjk116's comment, note that the for loops inside a comprehension are written in the same order that you would use with ordinary imbricated loops:

out = []
for sublist in zip(a, b, c):
    for item in sublist:
        out.append(item)
print(out)
# [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6]
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • Can you explain how this works? I'm used to list comprehensions with a single list like `[g(x) for x in mylist]`, but this is confusing me. Is this a list comprehension on a list comprehsion? Where does sublist on the right most side get define? – bjk116 Dec 20 '19 at 14:41
2

You could achieve that using numpy.

import numpy as np

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

d = np.array([a, b, c]).flatten('F')  # -> [1 2 3 2 3 4 3 4 5 4 5 6]
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22
1

this is an alternative version of leetcode 48 rotated images and add flatten..still simple:

mat = [a,b,c]
mat[::] = zip(*mat)
[item for sublist in mat for item in sublist]
Han.Oliver
  • 525
  • 5
  • 8
1

As Thierry pointed out, we need to transpose the list by using zip(a,b,c) and do a concatenation of a new list.

This is pretty fast (in both terms of performance and code-readability) way to do it using builtin package itertools:

from itertools import chain
result = list(chain(*zip(a,b,c)))

or, not using unpacking of arguments:

result = list(chain.from_iterable(zip(a,b,c)))

This was quite classical. But, surprise, Python has an another package called more_itertools that helps to do more advanced iterations. You need to install it and use:

from more_itertools import interleave
result = list(interleave(a,b,c))
mathfux
  • 5,759
  • 1
  • 14
  • 34