Use the * operator to zip a list of lists in Python. Another way is to use a combination of itertools.chain() + zip() methods.
Python zip list of lists
Simple example code.
a = [[2, 4], [6, 8], [10, 12]]
b = [['a', 'b', 'c'], ['1', '2', '3']]
res = zip(*a, *b)
print(list(res))
Output:
Let’s a combination of these itertools.chain() and zip() functions. The chain() function can perform the inter-list aggregation, and the final aggregation is done by the zip() method.
import itertools
a = [[2, 4], [6, 8], [10, 12]]
b = [['a', 'b', 'c'], ['1', '2', '3']]
op = [list(itertools.chain(*i))
for i in zip(a, b)]
print(list(op))
Output:
[[2, 4, ‘a’, ‘b’, ‘c’], [6, 8, ‘1’, ‘2’, ‘3’]]
An efficient way to zip a list with lists nested in another list in Python
Use *
operator (Read doc Unpacking Argument Lists)
a = [1, 2, 3]
b = [['a', 'b', 'c'], ['1', '2', '3']]
res = zip(a, *b)
print(list(res))
Output:
[(1, ‘a’, ‘1’), (2, ‘b’, ‘2’), (3, ‘c’, ‘3’)]
Do comment if you have any doubts or suggestions on this Python zip topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.