Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to merge two lists like a zip with for loop

I am given a problem where I have a function that takes two integer lists and returns a single integer list (new list) with the two integer lists zipped together.

For example:

list1 = [1,2,3]
list2 = [4,5,6]

Should give [1, 4, 2, 5, 3, 6] not [1, 2, 3, 4, 5, 6]

Another case is if one list is longer than another, e.g:

list1 = [1,2]
list2 = [4,5,6,9]

Once the shorter list runs out of items, the longer list should add its remaining elements. E.g: [1, 4, 2, 5, 6, 9]

I have tried using conditional statements to check which list is longer and use a for loop to append to a new list that should be returned. I tried using for loops that loop for the duration of the shorter list, and once the for loop is over, it adds the remaining elements from longer list to the new list. Also if both lists are empty I have to return an empty new list.

The code:

def main():
    list1 = [1,2]
    list2 = [4,5,6,9]
    print(zip_lists(list1, list2))

def zip_lists(list1, list2):
    new_list = []

    if len(list1) > len(list2):
        last_num = list1[len(list1):]
        for num in range(0, len(list2)):
            new_list.append(list1[num])
            new_list.append(list2[num])
        new_list.append(last_num)
        return new_list

    elif len(list2) > len(list1):
        last_num = list2[len(list2):]
        for num in range(0, len(list1)):
            new_list.append(list1[num])
            new_list.append(list2[num])
        new_list.append(last_num)
        return new_list


    elif len(list1) and len(list2) == 0:
        return new_list


main()

However, I have a problem where I cannot add the remaining elements from the longer list and instead returns a partially zipped list with empty square brackets.

The test case:

list1 = [1,2]
list2 = [4,5,6,9]

Should be [1, 4, 2, 5, 6, 9] but I'm getting [1, 4, 2, 5, []].

Is my code showing the right way of thinking about this problem?

like image 591
Jeze628 Avatar asked Jan 21 '26 06:01

Jeze628


1 Answers

def zip_lists(list1, list2):
    n1=len(list1)
    n2=len(list2)
    k = []
    n = min(n1, n2)
    for i in range(n):
        k.append(list1[i])
        k.append(list2[i])

    if n1==n2:
        return k 
    if n1>n2:
        return k+list1[n:]
    else:
        return k+list2[n:]

Test:

list1 = [1,2]
list2 = [4,5,6,9]
zip_lists(list1, list2) 

Output: [1, 4, 2, 5, 6, 9]

like image 101
ComplicatedPhenomenon Avatar answered Jan 23 '26 21:01

ComplicatedPhenomenon