How do I combine two lists of strings at every other element?

Viewed 103

How would I go from

lst1 = ['the', 'brown', 'jumps', 'the', 'dog']
lst2 = ['quick', 'fox', 'over', 'lazy']

to this output:

['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

without defining a new function?

So far I've tried:

insertcounter = 1
for k in lst2:
    lst1.insert(insertcounter, k)
    insertcounter += 1

But it's just inserting the entire lst2 at the first index instead of looping through. I'm sure the answer is in plain sight but I'm a noob and it's not hitting me.

Thanks in advance!

6 Answers

Change insertcounter += 1 to insertcounter += 2.

Just for fun, I will try this way:

It's similar with roundrobin but maybe faster: it produces the same output as roundrobin(), but may perform better for some inputs (in particular when the number of iterables is large). If the interables is small, it prob. will make a big difference though.

For the sake of completely honest with this lib, you have to install it first by doing pip install more_itertools. Thanks @Matiiss reminder.

>>> from more_itertools import interleave_longest
>>> list(interleave_longest(lst1, lst2))
['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
>>> 

You could do it using range and zip:

lst1 = ['the', 'brown', 'jumps', 'the', 'dog']
lst2 = ['quick', 'fox', 'over', 'lazy']

for i, word in zip(range(1, len(lst2)*2, 2), lst2):
    lst1.insert(i, word)

print(lst1)
# ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

TIO

You could loop over the range of the longer list and trap IndexError exceptions as needed:

lst1 = ['the', 'brown', 'jumps', 'the', 'dog']
lst2 = ['quick', 'fox', 'over', 'lazy']
out = []
for i in range(len(lst1)):
    try:
        out.append(lst1[i])
        out.append(lst2[i])
    except IndexError:
        continue

print(out)

Result:

['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

You can use itertools.zip_longest to iterate over the lists together even if the lists have different length:

import itertools

output = []
for i,j in itertools.zip_longest(lst1, lst2):
   output.append(i)
   if j:
       output.append(j)
print(output) 
lst1 = ['the', 'brown', 'jumps', 'the', 'dog',"murat"]
lst2 = ['quick', 'fox', 'over', 'lazy',"ali"]

newList=[]

if(len(lst1)>len(lst2)):
    for i in range(len(lst1)):
        newList.append(lst1[i])
        if(len(lst2)>i):
            newList.append(lst2[i])
else:
    for i in range(len(lst2)):
        newList.append(lst2[i])
        if(len(lst1)>i):
            newList.append(lst1[i])

print(newList)
Related