What is zip() function in Python?

Last updated 3 weeks, 5 days ago | 28 views 75     5

Tags:- Python

Python | zip() Function

Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator, and aggregates the elements based on the iterable passed. It returns an iterator of tuples. e.g: zip(iterator1, iterator2, iterator3 ...)  

 

In zip() function, the first item in each passed iterator is paired together, and then the second item in each passed iterator is paired together, etc.

Syntex:  zip(iterator1, iterator2, iterator3 ...) 

a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica")

x = zip(a, b)


print(x)        #(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))

 

If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
 

a = ("John", "Charles", "Mike")
b = ("Jenny", "Christy", "Monica", "Vicky")

x = zip(a, b)


print(x)        #(('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica'))