DEV Community

qing
qing

Posted on

TIL: zip() in Python 3.10+ Has a strict Mode to Catch Length Mismatches

TIL: zip() in Python 3.10+ Has a strict Mode to Catch Length Mismatches

In Python 3.10 and later, the built-in zip() function has a new strict parameter that can help catch length mismatches between input iterables. By default, zip() silently truncates the longer iterable to match the length of the shorter one. However, when strict=True is passed, zip() raises a ValueError if the input iterables have different lengths.

Here's an example:

a = [1, 2, 3]
b = ['a', 'b']

# Silent truncation (default behavior)
for x, y in zip(a, b):
    print(x, y)  # Output: 1 a, 2 b

# Strict mode
try:
    for x, y in zip(a, b, strict=True):
        print(x, y)
except ValueError as e:
    print(e)  # Output: zip() arguments are of unequal length
Enter fullscreen mode Exit fullscreen mode

As shown, the strict=True mode helps detect length mismatches, which can be particularly useful when working with data that's expected to have a specific structure.

The takeaway is that using zip() with strict=True can help prevent subtle bugs by explicitly raising an error when input iterables have different lengths.


Follow me on Dev.to for daily Python tips and quick guides!


If you found this useful, you might like Python Interview Prep Guide — a practical resource that takes things a step further. At $24.99 it's a solid investment for your toolkit.

Top comments (0)