Zip Function In Python

Function Name:

zip(*iterables)

Overview:

  • The zip()built-in function makes an iterator of tuples from multiple iterables.
  • An element of the returned iterator is a tuple comprising of the ith element from each of the input iterables.
  • The returned iterator stops when the iterable with the least element count exhausts.

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 2020 © pythontic.com