0

I have two lists like:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

I would like to combine them to get:

l = [1, 4, 2, 5, 3, 6]

How can I do this without using loops?

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Mike
  • 49
  • 3

5 Answers5

1

You can use itertools and zip:

Code:

import itertools as it
list(it.chain(*zip(listone, listtwo)))

Test Code:

listone = [1, 2, 3]
listtwo = [4, 5, 6]
print(list(it.chain(*zip(listone, listtwo))))

Results:

[1, 4, 2, 5, 3, 6]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
1

You may use list slicing feature of the list as:

>>> new_list = listone + listtwo  # create initial list of `len` equal
                                  # to `listone + listtwo`
>>> new_list[::2] = listone
>>> new_list[1::2] = listtwo
>>> new_list
[1, 4, 2, 5, 3, 6]

Another very simple way to achieve this is via using zip() with nested list comprehension expression as:

>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]

>>> [b for a in zip(listone, listtwo) for b in a]
[1, 4, 2, 5, 3, 6]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

this is a variant using zip and a nested list comprehension:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

l = list(a for ab in zip(listone, listtwo) for a in ab)
print(l)  # [1, 4, 2, 5, 3, 6]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
-1

You can use numpy (as here)

import numpy as np

listone = [1, 2, 3] 
listtwo = [4, 5, 6]

l=np.empty((len(listone)+len(listtwo)))
l[0::2]=listone
l[1::2]=listtwo

print l
>>> l = [ 1.  4.  2.  5.  3.  6.]
Community
  • 1
  • 1
-2

You can plus two lists directly .

list_one=[1,2,3]  
list_two=[4,5,6]  
list_one=list_one+list_two  
print(list_one)

>>>list_one=[1,2,3,4,5,6]      

you can also change the order of sum , then print out [4,5,6,1,2,3].

Yuguo Xie
  • 1
  • 1