Skip to content
Advertisement

Create iterator to return elements from each iterable one by one

I was learning the itertools module and I am trying to make an iterator to return each element from the iterables provided as input.

JavaScript

with one more rider that if say the lists are not of the same length then next(it) should return elements from the longer list when the shorter one runs out.

Attempt at solution

JavaScript

Which kind of solves my problem

JavaScript

Outputs:

JavaScript

Is there an easier or better way to do this? I searched for a solution on SO and was not able to get one.

Advertisement

Answer

You can use itertools.chain.from_iterable() to flatten the sequence, and use a generator expression to filter out the None values:

JavaScript

Rather than use None as the sentinel value, you may want to use a dedicated sentinel so you can use None in the input list:

JavaScript

If you want to filter out falsey values, then you can also use filter(None, ...):

JavaScript

Demo:

JavaScript

and with a local sentinel:

JavaScript

The itertools recipes section also has:

JavaScript
Advertisement