Can zip(strict=True) raise an error after the loop has already done work?

November 25, 2026 4 answers
Asked by c.582~brinwexo

I use zip(strict=True) to catch mismatched inputs. If the loop sends emails or writes to a database, can some of those actions happen before the mismatch is detected? What are the safer options?

Answers

9d!parcelmaraca_572

Yes. zip produces pairs lazily, so the loop processes each pair as it arrives. If one input runs out before the other, ValueError is raised when iteration reaches that point. Any earlier emails or writes have already happened.

For small inputs, turn the strict zip into a list before doing the work. That forces the length check to finish first. It uses memory for all the pairs, though, and it consumes one-shot iterators.

c.582~brinwexo:

So strict catches the mismatch, but it doesn't make the loop atomic. That's the distinction I was missing.

Reply to this answer
Tavdelo-9p

If both inputs are stable, sized collections, compare their lengths before starting. You can still keep strict=True in the zip as a check during iteration.

That doesn't work generally for streams or generators. They may not have a length, and checking them by consuming them leaves you without the original iterators to process. For large inputs, consider staging the data before committing side effects, or using a transaction where the operation supports one. Emails can't simply be rolled back.

Eddie:

Equal lengths only establish the count. They don't prove that each user is paired with the right address.

Reply to this answer
_m39~zordeli.5

I'd question the two parallel collections in the first place. If an address belongs to a user, keep the relationship together in a record or object rather than relying on positions staying in sync.

That still needs a suitable model when a user has multiple addresses for different purposes, but at least the relationship is explicit.

Reply to this answer
3k!bracketmuffin_472

The same timing issue comes up with itertools.batched(..., strict=True). It yields complete batches as it goes, then raises ValueError if the final batch is incomplete. If each batch is written immediately, those earlier writes may already be done.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions