I am looking for a nice way to zip
several iterables raising an exception if the lengths of the iterables are not equal.
In the case where the iterables
I can think of a simpler solution, use itertools.zip_longest()
and raise an exception if the sentinel value used to pad out shorter iterables is present in the tuple produced:
from itertools import zip_longest
def zip_equal(*iterables):
sentinel = object()
for combo in zip_longest(*iterables, fillvalue=sentinel):
if sentinel in combo:
raise ValueError('Iterables have different lengths')
yield combo
Unfortunately, we can't use zip()
with yield from
to avoid a Python-code loop with a test each iteration; once the shortest iterator runs out, zip()
would advance all preceding iterators and thus swallow the evidence if there is but one extra item in those.