'Why does Python `zip()` return an empty range of empty tuple
As zip takes the length from the shortest list, I would expect that passing zero argument to zip would result in an infinite range of empty tuple, instead of an empty range of empty tuple
Edit: Why infinite range
First, please refer to wikipedia of the either of empty product https://en.wikipedia.org/wiki/Empty_product
Product of numbers
>>> math.prod([])
1
The multiplication of zero numbers is 1. Because 1 is the identity of multiplication. 1 * x is x
Logic AND of booleans
>>> all([])
True
All of zero booleans is True, because True is the identity of logical AND. True and x is x
Logic OR of booleans
>>> any([])
False
any of zero booleans is False, because False is the identity of logical OR. False or x is x
Cartesian Product
>>> list(itertools.product())
[()]
Note that the above result is a range of exact one element of an empty tuple, which is equivalent of itertools.product(indentity)
The identity of cartesian product should be a range of exact one element of void, because if you do a cartesian product between that range with an arbitrary range x, you get x back.
What about zip
What is the identity? If you zip a range with an infinite range of void with a range x, as x is the shortest range so the result's length is x's length, and because the first range's element is void (conceptually), the result element is the same as x. so zip() should result in zip(repeat(())
Does this make sense?
Solution 1:[1]
PEP 201 and related discussion show that zip() with no arguments originally raised an exception. It was changed to return an empty list because this is more convenient for some cases of zip(*s) where s turns out to be an empty list. No consideration was given to what might be the 'identity', which in any case appears difficult to define with respect to zip - there is nothing you can zip with arbitrary x that will return x.
The original reasons for certain commutative and associative mathematical functions applied to an empty list to return the identity by default are not clear, but may have been driven by convenience, principle of least astonishment, and the history of earlier languages like Perl or ABC. Explicit reference to the concept of mathematical identity is rarely if ever made (see e.g. Reason for "all" and "any" result on empty lists). So there is no reason to rely on functions in general to do this. In many cases it would be less surprising for them to raise an exception instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stuart |
