Shivkumar Shivkumar - 1 month ago 7
Python Question

alternately appending elements from two lists

I have three lists with elements :

a = [[0,1],[2,3],...]
b = [[5,6],[7,8],...]

c = []


I want to append elements from
a
and
b
into
c
to get:

c = [ [0,1],[5,6],[2,3],[7,8],.... ]

Answer

Basic approach:

>>> a = [[0,1],[2,3]]
>>> b = [[5,6],[7,8]]
>>> c = []
>>> for pair in zip(a,b):
...   c.extend(pair)
... 
>>> c
[[0, 1], [5, 6], [2, 3], [7, 8]]
>>> 

This breaks if the lengths aren't equal. But you can deal with that case as an exercise.