brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: zip(strict=True) makes Python complain when two lists differ in length

Python
~/tips/tip-python-zip-strict

for name, email in zip(names, emails, strict=True):

Raises an error when the lists you zip together don't have the same length.

Python’s zip() has a habit I don’t love: when one list is shorter, it stops at the shortest one and says nothing. The extra items just vanish. Since Python 3.10 you can ask it to complain instead.

for name, email in zip(names, emails, strict=True):
    send_invite(name, email)

With strict=True the loop runs exactly as before as long as both lists are the same length. When they aren’t, you get a ValueError as soon as one of them runs out early. This is the example from the Python docs:

>>> for item in zip(range(3), ['fee', 'fi', 'fo', 'fum'], strict=True):
...     print(item)
...
(0, 'fee')
(1, 'fi')
(2, 'fo')
Traceback (most recent call last):
  ...
ValueError: zip() argument 2 is longer than argument 1

I’d use it wherever two lists are supposed to line up, like the header and the values of a CSV row, or file names and their checksums. The docs make the case well: without it, a bug that gives you lists of different lengths is silenced and turns up somewhere else, where it’s much harder to find.

The caveat is visible in that output. zip is lazy, so the error only comes when it reaches the end. Three tuples were already printed before the ValueError, which means in the invite loop above three people would already have their mail. If a half-finished job is a problem, build the pairs first with list(zip(a, b, strict=True)) and only start working once that line has passed.

When the lists may differ on purpose and you want to keep every item, strict is the wrong tool: itertools.zip_longest() pads the short one with a value you choose. And if you’re on Python 3.14, map() got the same strict argument.

Further reading: zip() in the Python built-in functions

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link