Python

Python zip_longest() Function : Get Details with Implementation

Are you looking for the complete information on Python zip_longest() function? In this article, we will see how can use Python zip_longest() function with some examples.

 

Python zip_longest() function :

Suppose we have two iterators of different lengths. We iterate them together obviously one iterator must end up with another iterator. In this situation, the python zip_longest() function can fill up the position of empty iterable with some user-defined values.

In case the user does not define the fillvalue parameter, zip_longest() function fills None as the default value.

 

Step By Step Implementation of Python zip_longest() function :

Before we start the step by step implementation for zip_longest() function. Let’s understand iterators. Iterators are python objects of the sequence data. I am assuming that you all understand the list in python.

 

list_example=[100,200,300,400,500]

for i in list_example:

print(i)

Here this list_example is an iterator because we can iterator over its element. Not only list but tuple, string, dict are iterable python objects. Now, let us understand this above function.

Step 1 :

Firstly, Import the itertools module. Actually the above function is the member of itertools package in python.

import itertools

Step 2:

Secondly, Define the sequence/ iterable objects. Here the iterables are of different lengths.

seq1 =[100,200, 300, 400, 500, 600, 700, 800] 
seq2 =[5 , 15, 25]

We have defined two lists which are a sequence of some numeric value. As you can see here both are of different lengths.

Step3:

Above all and Most importantly, Call the Python zip_longest() function. Please refer to the below code.

print(*(itertools.zip_longest(seq1, seq2,fillvalue = "empty")))

Here “empty” will be an alternative sequence value after the second sequence length gets over. You will understand more when you see the full code together for this zip_longest() function.
Here is the full code with output.

import itertools
seq1 =[100,200, 300, 400, 500, 600, 700, 800]
seq2 =[5 , 15, 25]
print(*(itertools.zip_longest(seq1, seq2,fillvalue = "empty")))

 

zip_longest() function demo example

 

Note –

As I have already explained that fillvalue is an optional parameter with a default value is None. Let’s understand it with the above example.

 

import itertools 
seq1 =[100,200, 300, 400, 500, 600, 700, 800] 
seq2 =[5 , 15, 25]
print(*(itertools.zip_longest(seq1, seq2)))

 

zip_longest() function with default fillvalue

 

Thanks 

Data Science Learner Team