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:
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)
Output
[([1, 2], [7, 8]), ([3, 4], [9, 10]), ([5, 6], [11, 12])]
Explanation:
zip()function pairs corresponding sublists froml1andl2.- Combines these pairs into a list of tuples.
Let's explore more method to zip two list of list.
Table of Content
Using itertools.zip_longest
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:
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)
Output
[([1, 2], [5, 6]), ([3, 4], [7, 8]), ([], [9, 10])]
Explanation:
zip_longest()pairs sublists, filling missing values with[].- l
ist()converts the pairs into a list of tuples.
Using a Loop
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:
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)
Output
[[1, 3, 7, 9], [4, 5, 3, 2], [5, 6, 3, 10]]
Explantion:
- Combines corresponding sublists from
aandb. - Appends the combined sublists to
res.
Using numpy
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:
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)
Output
[[[ 1 2] [ 7 8]] [[ 3 4] [ 9 10]] [[ 5 6] [11 12]]]
Explanation:
- Pairs and converts sublists from
l1andl2into NumPy arrays. - Combines them into a 2D NumPy array.