Skip to content

Python zip() function

  • by

Python zip() function takes iterable or containers and returns a single iterator object. If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.

zip(iterator1, iterator2, iterator3 ...)

If we do not pass any parameter, zip() returns an empty iterator and If a single iterable is passed, zip() returns an iterator of tuples with each tuple having only one element.

Python zip() function

A simple example code zip two lists in Python.

l = ['Java', 'Python', 'JavaScript']
ver = [15, 4, 7]

res = zip(l, ver)

print(list(res))
print(type(res))

Output:

Python zip() function

Unzipping the Value Using zip()

Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator.

l = ['Java', 'Python', 'JavaScript']
ver = [15, 4, 7]

res = zip(l, ver)

c, v = zip(*res)

print(c)
print(v)

Output:

(‘Java’, ‘Python’, ‘JavaScript’)
(15, 4, 7)

Python zip enumerate

names = ['JOHN', 'Hary', 'Mike']
ages = [24, 50, 18]

for i, (name, age) in enumerate(zip(names, ages)):
    print(i, name, age)

Output:

0 JOHN 24
1 Hary 50
2 Mike 18

Do comment if you have any doubts or suggestions on this Python function 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.

Leave a Reply

Your email address will not be published. Required fields are marked *