Skip to content
Related Articles

Related Articles

Python – Itertools.zip_longest()
  • Last Updated : 27 Feb, 2020

Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

Iterators in Python is an object that can iterate like sequence data types such as list, tuple, str and so on.

Note: For more information, refer to Python Itertools

Itertools.zip_longest()

This iterator falls under the category of Terminating Iterators. It prints the values of iterables alternatively in sequence. If one of the iterables is printed fully, the remaining values are filled by the values assigned to fillvalue parameter.

Syntax:



zip_longest( iterable1, iterable2, fillval)

Example 1:




# Python code to demonstrate the working of   
# zip_longest()  
      
    
import itertools  
      
# using zip_longest() to combine two iterables.  
print ("The combined values of iterables is  : ")  
print (*(itertools.zip_longest('GesoGes', 'ekfrek', fillvalue ='_' )))  

Output:

The combined values of iterables is  : 
('G', 'e') ('e', 'k') ('s', 'f') ('o', 'r') ('G', 'e') ('e', 'k') ('s', '_')

Example 2:




from itertools import zip_longest
  
  
x =[1, 2, 3, 4, 5, 6, 7]
y =[8, 9, 10]
z = list(zip_longest(x, y))
print(z)

Output:

[(1, 8), (2, 9), (3, 10), (4, None), (5, None), (6, None), (7, None)]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :