Python | zip() in python

This post explains how to use zip() function in Python. zip() method iterate over several iterables in parallel, producing tuples with an item from each one.

zip() method returns a zip object. The zip object yields n-length tuples, where n is the number of iterables passed as positional arguments to zip(). The i-th element in every tuple comes from the i-th iterable argument to zip(). This continues until the shortest argument is exhausted.

In Python 3.10 zip function has been updated and it has now one more parameter strict which is having default value as False.

zip() function syntax in Python 3.10
   
    zip(*iterables, strict=False)
     
zip() function syntax in earlier versions of Python
       
    zip(*iterables)
     

zip() examples

Using zip on iterators of same lengths
   
    iterator_1 = [1, 2, 3, 4]
    iterator_2 = ["one", "two", "three", "four"]
    
    for item in zip(iterator_1, iterator_2):
        print(item)        
     
Output
   
    (1, 'one')
    (2, 'two')
    (3, 'three')
    (4, 'four')
     
Using zip on iterators on different lengths

While using zip on iterator of different lengths the iterator stops when the shortest input iterable is exhausted, refer below output.

   
    iterator_1 = [1, 2, 3, 4, 5, 6]
    iterator_2 = ["one", "two", "three", "four"]
    
    for item in zip(iterator_1, iterator_2):
        print(item)
     
Output
   
    (1, 'one')
    (2, 'two')
    (3, 'three')
    (4, 'four')
     
zip() with strict parameter

Note: strict parameter is available in Python 3.10, if you have earlier version of Python than below code snippet will not work.

With strict=False(default option) zip() stops when the shortest iterable is exhausted. It will ignore the remaining items in the longer iterables.

   
    iterator_1 = [1, 2, 3, 4]
    iterator_2 = ["one", "two", "three", "four"]    
    
    for item in zip(iterator_1, iterator_2, strict=True):
        print(item)
     
Output
   
    (1, 'one')
    (2, 'two')
    (3, 'three')
    (4, 'four')
     

With strict=True, it checks that the lengths of iterables are identical, if not than raises a valueError.

   
    iterator_1 = [1, 2, 3, 4, 5, 6, 7]
    iterator_2 = ["one", "two", "three", "four"]
    
    for item in zip(iterator_1, iterator_2, strict=True):
        print(item)
     
Output
   
    ValueError: zip() argument 2 is shorter than argument 1
     

Follow US on Twitter: