How to Zip List of Lists in Python

0
3116
Python Zip List of Lists with Example

The python zip() method returns a zip object, an iterator of tuples where the first element in each passed iterator is paired together. Then the second element in each given iterator is paired together, and the third, etc.

Python zip list of lists

To create a Python zip list of lists, define three different lists with the same number of elements 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))

Output

[('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 the second and third. We can combine the list of lists using the zip() method.

Unpacking arguments

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 unavailable separately, write the function call with the *-operator to unpack the arguments from a list or tuple.

# app.py

rdata = list(range(2, 8))
print(rdata)

args = [2, 8]
op = list(range(*args))
print(op)

Output

[2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6, 7]

There is another example of zip lists in a list.

# app.py

x = [1, 2]
y = [11, 22]
z = [111, 222]

op = zip(*[x, y, z])
print(list(op))

Output

[(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 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))

Output

[[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 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.

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.