Open In App

How to Zip two lists of lists in Python?

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let’s discuss certain ways in which solutions can be devised. 

Method #1: Using map() + __add__ 

This problem can be solved using the map function with the addition operation. The map function performs the similar kind of function as the zip function and in  this case can help to reach to a solution. 

Approach:

  1. Use the map() function to apply the list.__add__() method to each pair of sub-lists in test_list1 and test_list2, resulting in a new list of lists that combines the elements of each pair of sub-lists.
  2. Convert the resulting map object to a list and assign it to the variable res.
  3. Print the modified, zipped list res.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# zipping lists of lists
# using map() + __add__
 
# initializing lists
test_list1 = [[1, 3], [4, 5], [5, 6]]
test_list2 = [[7, 9], [3, 2], [3, 10]]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# using map() + __add__
# zipping lists of lists
res = list(map(list.__add__, test_list1, test_list2))
 
# printing result
print("The modified zipped list is : " + str(res))


Output :

The original list 1 is : [[1, 3], [4, 5], [5, 6]]
The original list 2 is : [[7, 9], [3, 2], [3, 10]]
The modified zipped list is : [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]

Time complexity: O(n), where n is the length of the longest list among test_list1 and test_list2.
Auxiliary space: O(n), where n is the length of the longest list among test_list1 and test_list2.

Method #2 : Using itertools.chain() + zip() 

This combination of these two functions can be used to perform this particular task. The chain function can be used to perform the interlist aggregation, and the intralist aggregation is done by zip function. 

Python3




# Python3 code to demonstrate
# zipping lists of lists
# using map() + __add__
import itertools
 
# initializing lists
test_list1 = [[1, 3], [4, 5], [5, 6]]
test_list2 = [[7, 9], [3, 2], [3, 10]]
 
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# using map() + __add__
# zipping lists of lists
res = [list(itertools.chain(*i))
       for i in zip(test_list1, test_list2)]
 
# printing result
print("The modified zipped list is : " + str(res))


Output :

The original list 1 is : [[1, 3], [4, 5], [5, 6]]
The original list 2 is : [[7, 9], [3, 2], [3, 10]]
The modified zipped list is : [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]

Time complexity: O(n), where n is the length of the input lists.
Auxiliary space: O(n), where n is the length of the input lists.

Method #3: Using list comprehension with extend()

This code initializes two lists of lists, test_list1 and test_list2. It then uses the built-in zip function to pair up the sublists from each list and uses list comprehension to iterate over the pairs of sublists. For each pair, it calls the extend() method on the first sublist to add the elements of the second sublist to it. Finally, it prints the original lists and the modified list.

Time complexity: O(n), where n is the total number of elements in the lists.
Auxiliary Space: O(n)
 

Python3




# Initialize two lists of lists
test_list1 = [[1, 3], [4, 5], [5, 6]]
test_list2 = [[7, 9], [3, 2], [3, 10]]
 
# Zip the two lists and use list comprehension to
# extend each sublist in test_list1 with the
# corresponding sublist in test_list2
res = [x.extend(y) for x, y in zip(test_list1, test_list2)]
 
# Print the original lists and the modified list
print("Original list 1:", test_list1)
print("Original list 2:", test_list2)
print("Modified list:", test_list1)
 
# This code is contributed by Edula Vinay Kumar Reddy


Output

Original list 1: [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]
Original list 2: [[7, 9], [3, 2], [3, 10]]
Modified list: [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]

Time complexity: O(n).
Auxiliary space: O(1).

Method #4: Using a loop to iterate over both lists and concatenate the sublists.

  1. Use a loop to iterate over the sublists in both lists and concatenate them using the + operator. 
  2. We then add the concatenated sublist to the result list. 
  3. Finally, we print the modified zipped list.

Python3




# initializing lists
test_list1 = [[1, 3], [4, 5], [5, 6]]
test_list2 = [[7, 9], [3, 2], [3, 10]]
 
# creating an empty list to store the concatenated sublists
res = []
 
# iterating over the range of indices of the sublists in test_list1
for i in range(len(test_list1)):
 
    # concatenating the sublists at index i
    # in test_list1 and test_list2
    concatenated_sublist = test_list1[i] + test_list2[i]
 
    # adding the concatenated sublist to the result list
    res.append(concatenated_sublist)
 
# Printing the modified zipped list
print("The modified zipped list is:", res)


Output

The modified zipped list is: [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]

Time complexity: O(n).
Auxiliary space: O(n).

Method #5: Using numpy.array() and numpy.concatenate()

Approach:

  1. Import the numpy module.
  2. Create numpy arrays from test_list1 and test_list2 using np.array() function.
  3. Concatenate the numpy arrays along the second axis (axis 1) using np.concatenate() function.
  4. Convert the concatenated numpy array to a nested list using tolist() method.
  5. Store the resulting nested list in the variable res.
  6. Print the modified zipped list.

Below is the implementation of the above approach:

Python3




import numpy as np
 
# Initializing lists
test_list1 = [[1, 3], [4, 5], [5, 6]]
test_list2 = [[7, 9], [3, 2], [3, 10]]
 
# Creating numpy arrays from test_list1 and test_list2
arr1 = np.array(test_list1)
arr2 = np.array(test_list2)
 
# Concatenating the numpy arrays along axis 1
concatenated_arr = np.concatenate((arr1, arr2), axis=1)
 
# Converting the concatenated numpy array to a nested list
res = concatenated_arr.tolist()
 
# Printing the modified zipped list
print("The modified zipped list is:", res)


Output

The modified zipped list is: [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]

Time complexity: O(n), where n is the total number of elements in the input lists.
Auxiliary space: O(n), where n is the total number of elements in the input lists.

Method #6: Using list comprehension with unpacking and zip()

Python3




# Python3 code to demonstrate
# zipping lists of lists
# using list comprehension with unpacking and zip()
 
# Initializing lists
test_list1 = [[1, 3], [4, 5], [5, 6]]
test_list2 = [[7, 9], [3, 2], [3, 10]]
 
# zipping lists of lists
# using list comprehension with unpacking and zip()
res = [[*x, *y] for x, y in zip(test_list1, test_list2)]
 
# Printing result
print("The modified zipped list is : " + str(res))


Output

The modified zipped list is : [[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]

Time complexity: O(n), where n is the total number of elements in the input lists.
Auxiliary space: O(n), where n is the total number of elements in the input lists.



Similar Reads

Create pandas dataframe from lists using zip
One of the way to create Pandas DataFrame is by using zip() function. You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe. zip() function creates the objects and that can be used to produce single item at a time. This function can create pandas DataFrames by mer
2 min read
Zip function in Python to change to a new character set
Given a 26 letter character set, which is equivalent to character set of English alphabet i.e. (abcd….xyz) and act as a relation. We are also given several sentences and we have to translate them with the help of given new character set. Examples: New character set : qwertyuiopasdfghjklzxcvbnm Input : "utta" Output : geek Input : "egrt" Output : co
2 min read
Python | Zip different sized list
In Python, zipping is a utility where we pair one list with the other. Usually, this task is successful only in the cases when the sizes of both the lists to be zipped are of the same size. But sometimes we require that different sized lists also to be zipped. Let's discuss certain ways in which this problem can be solved if it occurs. Method #1 :
4 min read
Python | Zip Uneven Tuple
In Python, zipping is a utility where we pair one record with the other. Usually, this task is successful only in cases when the sizes of both the records to be zipped are of the same size. But sometimes we require that different-sized records also be zipped. Let’s discuss certain ways in which this problem can be solved if it occurs. Method #1 : U
4 min read
Application to get address details from zip code Using Python
Prerequisite: Tkinter In this article, we are going to write scripts to get address details from a given Zip code or Pincode using tkinter and geopy module in python, Tkinter is the most commonly used GUI module in python to illustrate graphical objects and geopy is a python module to locate the coordinates of addresses, cities, countries, landmark
2 min read
Get Zip Code with given location using GeoPy in Python
In this article, we are going to write a python script to get the Zip code by using location using the Geopy module.geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world. To install the Geopy module, run the following command in your terminal. pip install geopy Approach:
2 min read
Python program for Zip, Zap and Zoom game
Zip zap zoom is a fun game that requires its players to concentrate and participate actively. When this game is played with people, this is how it is played: Players stand in a circle, 6 feet away from each otherOne player starts the game by clap-pointing and saying zap to the person on its leftThis person now does the same to the person to its rig
3 min read
Create Password Protected Zip of a file using Python
ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep re
2 min read
How to Brute Force ZIP File Passwords in Python?
In this article, we will see a Python program that will crack the zip file's password using the brute force method. The ZIP file format is a common archive and compression standard. It is used to compress files. Sometimes, compressed files are confidential and the owner doesn't want to give its access to every individual. Hence, the zip file is pro
3 min read
Use enumerate() and zip() together in Python
In this article, we will discuss how to use enumerate() and zip() functions in python. Python enumerate() is used to convert into a list of tuples using the list() method. Syntax: enumerate(iterable, start=0) Parameters: Iterable: any object that supports iterationStart: the index value from which the counter is to be started, by default it is 0 Py
3 min read
Practice Tags :
three90RightbarBannerImg