The zip() is a built-in function in Python that iterates over several iterable in parallel, producing tuples with an item from each one. In other words, returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument iterable.

Python Built-in Function zip:

The python zip function can be used to transpose a matrix. However, this function will not be processed until the iterable is iterated on using looping or by wrapping in a list. Moreover,  for iterable with different lengths, the zip() function will stop when the shortest iterable is over.

Signature

The signature for the zip() function is as shown below.

zip(Iterable1, iterable2,...,strict=False)

Parameters and return type

  • This function takes one or more iterable. The second parameter is strict with the default value False. When we want iterable to be of equal length, assign True value to strict.
  • However, it returns an iterator of tuples with values from iterable.

Python Built-in Function zip Examples:

Example 1:  For this example, let us demonstrate the zip function with a  list of serial numbers mapped to a menu item of a restaurant. Using for loop, we will print the tuples formed by the zip function.

#Initializing
n=[1,2,3,4,5]
m=["Pizza", "Pasta","Noodles","Frankie","Burger"]
#Using zip and Printing
for i in zip(n,m):
    print(i)

Output

(1, 'Pizza')
(2, 'Pasta')
(3, 'Noodles')
(4, 'Frankie')
(5, 'Burger')

Example 2: In this case, we will demonstrate the use of zip with an iterable of different lengths. Hence, it will form the tuples with the lowest number of items in the iterable.

n=[1,2,3,4,5]
m=["Pizza", "Pasta","Noodles"]
#Using zip and Printing
for i in zip(n,m):
    print(i)

Output

(1, 'Pizza')
(2, 'Pasta')
(3, 'Noodles')

Example 3: For this example, we will take a tuple and two lists as a parameter. Thereafter, we will form a list from these iterable. As we can see, only four tuples are formed as a location tuple has four elements.

#Initializing
n=[1,2,3,4,5]
m=["Pizza", "Pasta","Noodles","Burger","Frankie"]
l=("Delhi","Mumbai", "Pune","Banglore")
#Using zip and Printing
print(list(zip(n,m,l)))

Output

[(1, 'Pizza', 'Delhi'), (2, 'Pasta', 'Mumbai'), (3, 'Noodles', 'Pune'), (4, 'Burger', 'Banglore')]

Conclusion

The zip() function returns an iterator of tuples with elements from the iterator passed as a parameter. However, this function will raise an exception, if it is not iterated using looping or wrapping by a list.

References

Happy Learning 🙂