Zip() in Python

Zip() in Python

With the zip() method in Python, you may build an iterator that combines elements from multiple iterables. The resultant iterator can be used to efficiently and reliably address typical programming issues, such as building dictionaries.

zip in python

Python Zip()

In Python, zip() is a built-in function that is used for combining multiple iterables (such as lists or tuples) into a single iterable. It pairs elements from each input iterable based on their respective positions, creating tuples of elements.

Syntax :

zip(iterable1, iterable2, ...)

iterable1, iterable2 and so on are the input iterables that you want to combine.

The iterator that zip() returns creates tuples with elements from the input iterables. When the shortest input iterable is exhausted, the resulting iterator comes to an end. This means that zip() will only combine elements up to the length of the shortest iterable if the input iterables have different lengths.

Code 1:

Run
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c']

zip_list = zip(l1, l2)

for i in zip_list:
    print(i)

Output : 

(1, 'a')
(2, 'b')
(3, 'c')

We can easily unpack the tuple if needed and combine more than 2 iterables. Let’s understand it with an example:

Code 2 :

Run
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c']
l3 = [10, 20, 30]

zip_list = zip(l1, l2, l3)

for i in zip_list:
    a, b, c = i
    print(a, b, c)

Output :

1 a 10
2 b 20
3 c 30

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription