3

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]
yatu
  • 86,083
  • 12
  • 84
  • 139

5 Answers5

4

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]
yatu
  • 86,083
  • 12
  • 84
  • 139
2

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]
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
1

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)))
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
0

Here is another way:

joinedlist = [x for pair in zip(listone, listtwo) for x in pair]
Jim Eliot
  • 21
  • 3
0

U have many choice to get the output you expected.

  1. Use nested looping
x = []
for a in zip(listone, listtwo):
    for b in a:
        x.append(b)
  1. Single loop, just append and using index for a
x = []
for a in zip(listone, listtwo):
    x.append(a[0])
    x.append(a[1])
  1. And single line looping(more simple)
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]

Ilya Trianggela
  • 305
  • 1
  • 9