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?
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?
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]
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]
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]
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].