0

How to add two list up in alternate positions?

E.g. I have:

>>> x = [1,3,5,7,9]
>>> y = [2,4,6,8,10]

and when i add the list up, i get:

>>> x + y
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

but the desired output is:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I have tried this but is there other way to achieve the desired output?

>>> z = []
>>> for i,j in zip(x,y):
...     z.append(i)
...     z.append(j)
... 
>>> z
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
alvas
  • 115,346
  • 109
  • 446
  • 738

1 Answers1

2

You can use zip and a list comprehension:

>>> x = [1, 3, 5, 7, 9]
>>> y = [2, 4, 6, 8, 10]
>>> [b for a in zip(x, y) for b in a]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>

zip(x, y) is used to pair up the items in x and y:

>>> x = [1, 3, 5, 7, 9]
>>> y = [2, 4, 6, 8, 10]
>>> list(zip(x, y))
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
>>>

If you are using Python 2.x though, you may want to replace it with itertools.izip(x, y) so that you do not create a list unnecessarily.