0

If I have two lists:A=[1,2,3] ,B=[4,5,6].How to combine them like: C=[1,4,2,5,3,6]? Is there an effective way to do it, rather than do it like D=A[0]+B[0]+A[1]+B[1]+A[2]+B[2]?

yatu
  • 86,083
  • 12
  • 84
  • 139
  • Does this answer your question? [Fastest way to get union of lists - Python](https://stackoverflow.com/questions/35866067/fastest-way-to-get-union-of-lists-python) – Esko Piirainen Oct 13 '20 at 19:52

3 Answers3

1

Use zip to aggregate both iterables, and flatten the result with another level of iteration:

[i for t in zip(A,B) for i in t]
# [1, 4, 2, 5, 3, 6]
yatu
  • 86,083
  • 12
  • 84
  • 139
1

I'd slice.

>>> C, C[::2], C[1::2] = A+B, A, B
>>> C
[1, 4, 2, 5, 3, 6]
superb rain
  • 5,300
  • 2
  • 11
  • 25
0

Iterate through the list with a loop:

res = []
for i in range(min(len(A), len(B))):
  res.append(A[i])
  res.append(B[i])

This stops as soon as one of the lists is out of elements

Dennis
  • 27
  • 5