Python Zip List of Lists with Example
Python zip() method returns a zip object, which is an iterator of tuples where the first element in each passed iterator is paired together. Then the second element in each passed iterator is paired together, and third, etc.
Python Zip List of Lists
To create a Python zip list of lists, define three different lists with the same number of items and pass those lists to the zip() method, which will return the tuple iterator and then convert it into the list using the list() method.
# app.py stocks = ['reliance', 'infosys', 'tcs'] prices = [2175, 1127, 2750] sectors = ['Oil and Telecom', 'IT', 'IT'] zipped = zip(stocks, prices, sectors) print(list(zipped))
[('reliance', 2175, 'Oil and Telecom'), ('infosys', 1127, 'IT'), ('tcs', 2750, 'IT')]
You can see that it paired with the first item of each list, then second, and third. We can combine the list of lists using the zip() method.
The reverse situation occurs when the arguments are already in a list or tuple but have to be unpacked for a function call requiring separate positional arguments.
For example, the inbuilt range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple.
# app.py rdata = list(range(2, 8)) print(rdata) args = [2, 8] op = list(range(*args)) print(op)
[2, 3, 4, 5, 6, 7] [2, 3, 4, 5, 6, 7]
There is one another example to zip lists in a list.
# app.py x = [1, 2] y = [11, 22] z = [111, 222] op = zip(*[x, y, z]) print(list(op))
[(1, 11, 111), (2, 22, 222)]
Zipping two lists of lists
Until now, we have zipped the list of lists. Now, we will zip the two lists of lists. The standard zip() method enables us the functionality to aggregate the values in the container.
But sometimes, we have a use case in which we need to have multiple lists and to contain lists as index elements, and we need to merge/zip them together. This is quite an uncommon scenario, but the solution to it can still be easy.
To zip two lists of lists in Python, use the combination of itertools.chain() + zip() methods.
# app.py import itertools listA = [[2, 4], [6, 8], [10, 12]] listB = [[1, 3], [5, 7], [9, 11]] op = [list(itertools.chain(*i)) for i in zip(listA, listB)] print(list(op))
[[2, 4, 1, 3], [6, 8, 5, 7], [10, 12, 9, 11]]
The combination of this itertools.chain() and zip() functions can perform this particular job. The chain() function can be used to perform the inter-list aggregation, and the final aggregation is done by the zip() method.
That is it for the Python zip list of lists example.