DEV Community

Cover image for Python zip_longest() Function.
Shaila B
Shaila B

Posted on

Python zip_longest() Function.

Consider if we have two iterators of different lengths. then we iterate them together one iterator must end up with another iterator.

carbon (9).png
OUTPUT:

carbon (10).png
Here the elements 5 and 6 are missing. Because the zip() function will stop aggregating once the shortest iterable passed to it is exhausted.

It will make more sense if we would return a group that containing elements 5 and 6 otherwise it will be problematic.

In this situation, we can use zip_longest().

The python zip_longest() function can fill up the position of empty iterable with some user-defined values.

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

carbon (8).png
For Example :

carbon (11).png
OUTPUT:

carbon (12).png
In the above example, we imported zip_longest() function from itertools library.

We can observe in the above example those list y elements are filled with no value.

carbon (13).png
OUTPUT:

carbon (14).png
In the above example, list y elements fill with integer value as 1.

carbon (15).png
OUTPUT:

carbon (16).png
In the above example list y elements filled with float value as 1.5

carbon (17).png
OUTPUT:

carbon (18).png
In the above example list y is filled with a string value as 'Explore'.

carbon (19).png
OUTPUT:

carbon (20).png
In the above example list y is filled with boolean value True.

Latest comments (0)