Understand Python zip(*): Unzipping a Sequence with Examples – Python Tutorial

By | March 15, 2022

Python zip() function can pack a list of sequence to a python list. However, how about zip(*) in python? In this tutorial, we will use some examples to show you how to use it.

Python zip() function

It is easy to use zip() function, here is the tutorial:

Understand Python zip() Function – Python Tutorial

Python zip(*) function

This function can unzip result that packed by zip() function.

For example:

l1 = [1, 2, 3]
l2 = [4, 5, 5]

x = zip(l1, l2)
print(x)

x is a zip object, the value of it is [(1, 4), (2, 5), (3, 5)]

In order to unzip x, we can do as follows:

unzip_l1, unzip_l2 = zip(*x)

print(unzip_l1)
print(unzip_l2)

Run this code, we will see:

(1, 2, 3)
(4, 5, 5)

We can find: l1 is python list, however, unzip_l1 is python tuple.

There is an interesting thing, look at code below:

l1 = [1, 2, 3]
l2 = [4, 5, 5]

x = zip(l1, l2)
print(x)
for e in x:
    print(e)

unzip_l1, unzip_l2 = zip(*x)

print(unzip_l1)
print(unzip_l2)

We print all values in x before we unzipping it. Run this code, we will see:

<zip object at 0x7f5d09a72f08>
(1, 4)
(2, 5)
(3, 5)
Traceback (most recent call last):
  File "/home/test.py", line 9, in <module>
    unzip_l1, unzip_l2 = zip(*x)
ValueError: not enough values to unpack (expected 2, got 0)

A ValueError is reported, which means x can not be iterated before unzipping it.

Leave a Reply