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]