How do I concatenate two lists while taking elements 1 by 1 in Python?
Example:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
Expected outcome:
>>> joinedlist
[1, 4, 2, 5, 3, 6]
zip
the lists and flatten with itertooos.chain
:
from itertools import chain
list(chain.from_iterable(zip(listone, listtwo)))
[1, 4, 2, 5, 3, 6]
Using just list_comprehensions
and no other fancy library you can do this:
In [825]: [j for i in zip(listone, listtwo) for j in i]
Out[825]: [1, 4, 2, 5, 3, 6]
Here is a simple way:
x = []
for a in zip(listone,listtwo):
x.extend(a)
x
Or if you want some black magic with chain from itertools:
list(chain(*zip(listone,listtwo)))
Here is another way:
joinedlist = [x for pair in zip(listone, listtwo) for x in pair]
U have many choice to get the output you expected.
x = []
for a in zip(listone, listtwo):
for b in a:
x.append(b)
x = []
for a in zip(listone, listtwo):
x.append(a[0])
x.append(a[1])
x = [x for i in zip(listone, listtwo) for x in i]
If u print x
for each point, the output will be: [1, 4, 2, 5, 3, 6]