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]
?
Asked
Active
Viewed 142 times
0

yatu
- 86,083
- 12
- 84
- 139

Chen Jeremiah
- 3
- 2
-
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 Answers
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
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