Last Updated : 11 Jul, 2025
zip()
function typically aggregates values from containers. However, there are cases where we need to merge multiple lists of lists. In this article, we will explore various efficient approaches to Zip two lists of lists in Python. List Comprehension provides a concise way to zip two lists of lists together, making the code more readable and often more efficient than using the zip()
function with additional operations.
Example:
Python
l1 = [[1, 2], [3, 4], [5, 6]]
l2= [[7, 8], [9, 10], [11, 12]]
# Zipping list
res = [(a, b) for a, b in zip(l1, l2)]
print(res)
[([1, 2], [7, 8]), ([3, 4], [9, 10]), ([5, 6], [11, 12])]
Explanation:
zip()
function pairs corresponding sublists from l1
and l2
.Let's explore more method to zip two list of list.
This method
allows us to zip two lists of different lengths, padding the shorter list with a specified default value. This ensures that both lists are iterated over completely, even if they have unequal lengths.
Example:
Python
import itertools
a= [[1, 2], [3, 4]]
b= [[5, 6], [7, 8], [9, 10]]
#Zipping with padding
res = list(itertools.zip_longest(a, b, fillvalue=[]))
print(res)
[([1, 2], [5, 6]), ([3, 4], [7, 8]), ([], [9, 10])]
Explanation:
zip_longest()
pairs sublists, filling missing values with []
.ist()
converts the pairs into a list of tuples.This method uses a loop to iterate through corresponding sublists in two lists and concatenate them with the +
operator. The concatenated sublists are then added to a result list, which is printed at the end.
Example:
Python
a = [[1, 3], [4, 5], [5, 6]]
b = [[7, 9], [3, 2], [3, 10]]
res = []
# Iterating and concatenating sublists
for i in range(len(a)):
res.append(a[i] + b[i])
print(res)
[[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]
Explantion:
a
and b
.res
.When we are dealing with large datasets, numpy
is a great choice for efficiency. It is specifically optimized for large-scale array operations and can perform zipping faster than standard Python lists when the data is numeric.
Example:
Python
import numpy as np
l1 = [[1, 2], [3, 4], [5, 6]]
l2 = [[7, 8], [9, 10], [11, 12]]
# Convert lists to numpy arrays
res = np.array([np.array([a, b]) for a, b in zip(l1, l2)])
print(res)
[[[ 1 2] [ 7 8]] [[ 3 4] [ 9 10]] [[ 5 6] [11 12]]]
Explanation:
l1
and l2
into NumPy arrays.RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4