Zip Function In Python

Function Name:

zip(*iterables)

Overview:

  • The Python built-in function zip() enables iterating multiple iterables in one go.

  • During each iteration the zip() function returns a tuple - comprising an item from each of the iterables passed in.

  • The zip() function can be passed iterables/containers of different types and lengths.

e.g., A list of two items, A list of three items and a dictionary of four name-value pairs.

Note: For associate containers like dictionary only the key will be picked-up during the

iteration. Not the value.

  • The parameter strict of the zip() function takes care of handling containers of varying lengths. If strict is True, an exception is raised when lengths of the containers are not equal. If strict is False, iteration continues till the length of the shortest container.

Parameters:

  • Iterables from which a single iterator to be made which will produce tuples of n length – where n is the number of parameters passed.

Return value:

  • Iterator that produces tuples consisting of ith elements from the input iterables.

Example:

# Example Python program to make an iterator of tuples

# from multiple iterables

 

# Create iterables...a list, a tuple and a set

collection1 = ["a", "e", "i", "o", "u"];

collection2 = (1, 2, 3, 4, 5);

collection3 = {2, 4, 6, 8};

 

# Make a single iterator out of multiple iterables

zipped = zip(collection1, collection2, collection3);

 

print(type(zipped))

print("Contents of the iterator:");

for z in zipped:

    print(z);

 

Output:

<class 'zip'>

Contents of the iterator:

('a', 1, 8)

('e', 2, 2)

('i', 3, 4)

('o', 4, 6)

 


Copyright 2022 © pythontic.com