Signup/Sign In
PUBLISHED ON: FEBRUARY 2, 2021

Merge Lists into a List of Tuples

In this article, we will learn to merge multiple lists into a list of tuples in Python. We will use some built-in functions and some custom code as well. Let's first have a quick look over what is a list and a tuple in Python.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

list1 = ["Ram", "Arun", "Kiran"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]

Python Tuple

Python has a built-in data type called a tuple. Data inside a tuple can be of any type say, integer, string or a float value, or even a tuple type. The tuple uses comma-separated values within round brackets or parentheses to store data. Tuples can be defined using any variable name and then assigning different values to the tuple inside the round brackets. The tuple is ordered, unchangeable, and allows duplicate values.

tuple1 = ("Ram", "Arun", "Kiran")
tuple2 = (16, 78, 32, 67)
tuple3 = ("apple", "mango", 16, "cherry", 3.4)

Merge Lists into a List of Tuples

Lists can contain multiple items of different types of data. We can also combine lists data into a tuple and store tuples into a list. Let us discuss various ways to merge two or more lists into a list of tuples.

Example: Merge two or more Lists using one-liner code

The below example takes two lists to combine into one list of tuples. We use for loop to combine the lists. This method can be applied on multiple lists but the length of all the lists should be the same.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

new_list = [(list1[i], list2[i]) for i in range(0, len(list1))]

print(new_list)


[(1, 'a'), (2, 'b'), (3, 'c')]

Example: Merge lists using an efficient approach

The below example takes two lists and append() function is applied after iterating over the elements of each list. This method works well with uneven lengths of the two lists. It also provides a try catch error for IndexError.

list1 = [1, 2, 3] 
list2 = ['a', 'b', 'c'] 

new_list = [] 
for i in range(max((len(list1), len(list2)))):
    while True:
        try:
            tup = (list1[i], list2[i]) 
        except IndexError: 
            if(len(list1) > len(list2)):
                list2.append('') 
                tup = (list1[i], list2[i]) 
            elif(len(list1) < len(list2)):
                list1.append('') 
                tup = (list1[i], list2[i])
            elif(len(list1) < len(list2)):
                list1.append('') 
                tup = (list1[i], list2[i]) 
            continue

        new_list.append(tup) 
        break
print(new_list)


[(1, 'a'), (2, 'b'), (3, 'c')]

Example: Merge lists using using zip() function

The below example executes a one-liner code to merge two lists. Lists are passed to zip() function as arguments. zip() function combines corresponding elements from multiple sequences into a single list of tuples by typecasting. It is the cleaner way to merge elements from multiple lists. We can pass multiple lists of variable lengths to the zip() function. If the input sequences are of variable lengths, zip() will only match elements until the end of the shortest list is reached.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c', 'd']

new_list = list(zip(list1, list2))

print(new_list)


[(1, 'a'), (2, 'b'), (3, 'c')]

Example: Merge lists using zip() function with Unpacking

The below example uses an asterisk (*) operator with zip() function to merge lists. This is called unpacking. We use * to unpack all inner elements from a given list. Instead of passing all the lists one by one, this one-liner code makes it easier to pass only one list with *. Also, multiple input lists can be declared using a comma.

list1 = [[1, 2, 3],
['a', 'b', 'c', 'd'],
[0, 'Alice', 4500.00]]

new_list = list(zip(*list1))

print(new_list)


[(1, 'a', 0), (2, 'b', 'Alice'), (3, 'c', 4500.0)]

Example: Merge lists using enumerate()

The below example uses two for loops to enumerate through lists and merge the two lists.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

new_list = [(p1, p2) for idx1, p1 in enumerate(list1) 
           for idx2, p2 in enumerate(list2) if idx1 == idx2]

print(new_list)


[(1, 'a'), (2, 'b'), (3, 'c')]

Example: Merge lists using map() and lambda

The below example takes the lambda function as passes lists as arguments to merge into lists of tuples.

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

new_list = list(map(lambda x, y:(x,y), list1, list2))

print(new_list)


[(1, 'a'), (2, 'b'), (3, 'c')]

Conclusion

In this article, we learned to combine multiple lists into a list of a tuple in Python by using several built-in functions such as zip(), map(), lambda, enumerate, append() etc and we used some simple algorithms as well. We discussed that all these methods can merge two or more lists but some can only merge lists with even lengths.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.