0

I have 2 lists:

item1
item2
item3
.
.
itemX

and

item11
item22
item33
.
.
itemXX

I would like to merge those 2 lists into one by alternating the list elements so the resulting list will be like this:

item1
item11
item2
item22
.
.
itemX
itemXX

What is the best approach to do this in python?

What I am really trying to accomplish is to build a html table with X-rows and 2 columns so I need alternating lines with elements from both lists so that elements from list1 will go to column 1 and same for list2.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Cat Hariss
  • 123
  • 10
  • 2
    Best thing to do: code it. Come back if you have a specific question related to [mcve] that is a problem - currently you are just asking _us_ to code for you . – Patrick Artner Feb 20 '19 at 09:56
  • 1
    Dupe: [pythonic-way-to-combine-two-lists-in-an-alternating-fashion](https://stackoverflow.com/questions/3678869/pythonic-way-to-combine-two-lists-in-an-alternating-fashion) – Patrick Artner Feb 20 '19 at 09:57
  • 1
    and here https://stackoverflow.com/questions/7946798/interleave-multiple-lists-of-the-same-length-in-python – Arran Duff Feb 20 '19 at 10:00
  • 1
    and here [using-linq-and-c-is-it-possible-to-join-two-lists-but-with-interleaving-at-each-line](https://stackoverflow.com/questions/1758404/using-linq-and-c-is-it-possible-to-join-two-lists-but-with-interleaving-at-each-line) – Patrick Artner Feb 20 '19 at 10:02

1 Answers1

1
import itertools
foo=[1,3,5,7,9]
bar=[2,4,6,8,10,12,14]
new_list=[]
for f,b in itertools.zip_longest(foo,bar):
    if f:
        new_list.append(f)
    if b:
        new_list.append(b)
print(new_list)
sujeet14108
  • 568
  • 5
  • 19