Home > Software engineering >  How to interleave elements from two lists in python
How to interleave elements from two lists in python

Time:12-02

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = list1   list2
print(list3)

output ---

['a', 'b', 'c', 1, 2, 3]

but I want output like this ---

['a',1,'b',2,'c',3]

please help me

CodePudding user response:

You can create a for loop and use zip and extend:

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = []
for items in zip(list1, list2):
    list3.extend(items)

print(list3)

Alternatively a list comprehension (however it is both slower and less readable, still will keep it here just for information as to how to handle cases where an iterable has to be extended in a comprehension)

list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

list3 = [c for items in zip(list1, list2) for c in items]
print(list3)

CodePudding user response:

from itertools import chain
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

result = list(chain(*zip(list1, list2)))
print(result)

As a [better] alternative (because argument you pass to .from_iterable() will be evaluated lazily), as mentioned by @juanpa.arrivillaga:

result = list(chain.from_iterable(zip(list1, list2)))

CodePudding user response:

A brute-force merge will go something like this:

list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list3 = []

## merge two list with output like ['a',1,'b',2,'c',3]
for i in range(len(list1)):
    list3.append(list1[i])
    list3.append(list2[i])

print(list3)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

A better way is to use itertool or chain as above!

CodePudding user response:

If the lists of the same length, you can zip the lists and use list.extend method:

new_list = []
for ij in zip(list1,list2):
    new_list.extend(ij)
print(new_list)

Output:

['a', 1, 'b', 2, 'c', 3]
  • Related