merge two lists alternatively in python

Merge Two Lists Alternatively in Python

In this tutorial, we will look at how to merge two lists alternatively in Python with the help of some examples.

The Problem Statement

merge two lists alternatively in python

Before we proceed let’s look at what we actually mean by merging two lists alternatively.

Let’s say you are given two lists, list1 and list2 and you’re asked to merge the two lists together into a new list such that it contains elements from both lists alternatively starting from the first list. Not that the lists need not necessarily be of the same length.

For example,

list1 has the elements [a1, a2, a3]
list2 has the elements [b1, b2, b3]

After merging, the resulting list should look like [a1, b1, a2, b2, a3, b3].

Let’s look at another example where the lists are not of the same length.

list1 has the elements [a1, a2, a3, a4, a5]
list2 has the elements [b1, b2, b3]

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

After merging, the resulting list should look like [a1, b1, a2, b2, a3, b3, a4, a5]. You can see that the remaining elements from the larger list were appended at the end of the resulting list.

How to merge two lists alternatively?

We will create a new list resulting from alternatively merging the elements of the two lists. You can use the following steps –

  1. Create variables to keep track of the current index in both lists.
  2. Create a boolean flag to alternate between the two lists.
  3. Create the resulting list as an empty list.
  4. Use a while loop to iterate through the lists alternating between the two lists using the flag created above. The loop stops if either of the index variables reaches the end.
  5. Finally, concatenate the remaining elements (if the lists are not of the same lengths) to the resulting list.

Let’s look at the code.

# function to merge two lists alternatively
def merge_two_lists_alternatively(ls1, ls2):
    # create variables to keep track of indices
    i = 0
    j = 0
    # flag to alternate between the lists
    flag = True
    # the resulting list
    res = []

    # iterate through the list elements alternatively
    while i < len(ls1) and j < len(ls2):
        if flag:
            res.append(ls1[i])
            i += 1
            flag = False
        else:
            res.append(ls2[j])
            j += 1
            flag = True

    # append the remaining elements
    if i == len(ls1):
        res = res + ls2[j:]
    else:
        res = res + ls1[i:]

    # return the resulting list
    return res

Merge Lists of the Same Length

Let’s now use the above code to merge two lists of the same length alternatively.

# the two lists to be merged
ls1 = ['a1', 'a2', 'a3']
ls2 = ['b1', 'b2', 'b3']

# merge lists alternatively
ls = merge_two_lists_alternatively(ls1, ls2)
print(ls)

Output:

['a1', 'b1', 'a2', 'b2', 'a3', 'b3']

You can see that the resulting list contains alternate elements from ls1 and ls2.

Merge Lists of Different Lengths

Let’s now apply the above method to two lists that do not have the same length.

# the two lists to be merged
ls1 = ['a1', 'a2', 'a3', 'a4', 'a5']
ls2 = ['b1', 'b2', 'b3']

# merge lists alternatively
ls = merge_two_lists_alternatively(ls1, ls2)
print(ls)

Output:

['a1', 'b1', 'a2', 'b2', 'a3', 'b3', 'a4', 'a5']

You can see that the remaining elements are appended at the end.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top