Python zip_longest() Function.

Shaila B
3 min readJul 30, 2021

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

OUTPUT:

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.

For Example :

OUTPUT:

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.

OUTPUT:

In the above example, list y elements fill with integer value as 1.

OUTPUT:

In the above example list y elements filled with float value as 1.5

OUTPUT:

In the above example list y is filled with a string value as ‘Explore’.

OUTPUT:

In the above example list y is filled with boolean value True.

--

--