Unknown
Unknown

Reputation: 9

Merging 2 list elementwise vertically python

I have 2 lists:

a=[1,2,3,4]
b=[5,6]

I want to merge to make list c such that final answer is

c=[1,5,2,6,3,4]

I don't want to use any built-in modules I tried zip but it stops at shorter list

Upvotes: 0

Views: 174

Answers (4)

sahasrara62
sahasrara62

Reputation: 11228

using loops only

a=[1,2,3,4]
b=[5,6]
 
i = 0
j = 0
 
result =[]
while i<len(a) or j <len(b):
    if i <len(a):
        result.append(a[i])
        i+=1
    if j < len(b):
        result.append(b[j])
        j+=1
 
print(result) # [1,5,2,6,3,4]

Upvotes: 0

mozway
mozway

Reputation: 260470

Use more_itertools.roundrobin:

# pip install more-itertools
from more_itertools import roundrobin

c = list(roundrobin(a,b))

output: [1, 5, 2, 6, 3, 4]

without installing more-itertools, you can also use the itertools recipe:

from itertools import cycle, islice
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    num_active = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while num_active:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            # Remove the iterator we just exhausted from the cycle.
            num_active -= 1
            nexts = cycle(islice(nexts, num_active))

Upvotes: 2

Aiden Chow
Aiden Chow

Reputation: 435

Here's one way without any built-in modules:

def merge(a, b):
  shorter_list = b if len(a) > len(b) else a
  longer_list = a if len(a) > len(b) else b
  return sum(zip(a, b), ()) + longer_list[len(shorter_list):]

Upvotes: 0

Amadan
Amadan

Reputation: 198324

Without using any builtin modules, this is probably the simplest — zip what is zippable, concatenate the rest:

s = min(len(a), len(b))
result = [e for pair in zip(a, b) for e in pair] + a[s:] + b[s:]

Upvotes: 1

Related Questions