The other day, PEP 618 (Add Optional Length-Checking To zip) was [committed that it was accepted](https://github. I saw com / python / peps / pull / 1435). So, this time I will read PEP 618.
zip ()
function, you may (often) implicitly expect each element to be the same length. >>> list(zip([1,2,3], [4])) # 2,3 will be lost
[(1, 4)]
def apply_calculations(items):
transformed = transform(items)
for i, t in zip(items, transformed):
yield calculate(i, t)
zip ()
and check that each element is the same lengthPython 3.10 added a parameter called strict
to thezip ()
function.
If you specify a positive value for strict
, ValueError
occurs when the lengths of the elements are not equal.
>>> for item in zip([1, 2, 3], [4], strict=True):
... print(item)
...
(1, 4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: zip() argument 2 is shorter than argument 1
I'm getting an error that the second argument of zip ()
is shorter than the first argument.
By the way, it should be noted that the loop runs until it detects that the lengths do not match.
By default, the behavior is the same as before (equivalent to strict = False
, that is, if the lengths are different, the data is discarded).
>>> for item in zip([1, 2, 3], [4]):
... print(item)
...
(1, 4)
>>>
strict = True
, so it may be a problem if you forget to specify it.Recommended Posts