This appears to be a relatively common problem to which there isn’t currently a de-facto solution. (At least as far as I know.)
Part of the reason why I believe this at least a fairly frequently seen issue is evidenced by this Stack Overflow question, where there are a huge volume of answers.
Feature or enhancement
Proposal:
def all_equal(iterable):
return all(map(operator.eq, iterable[1:], iterable[:-1])
Consider the following requirement for a function or operation:
- A function which takes as input an iterable and checks to see if all elements are equal
This is a fairly common requirement, but Python does not have a builtin function to support this. There are many ways to calculate the result using Python code, however for performance reasons a lazy-evaluated or short-circuit return builtin would be useful.
On the other hand, this operation can be composed from less complex operations.
- A “pairwise” version of
map
which rather than applying a unary function to an iterable applies a binary function to an iterable - The existing builtin function
all
, which is a short circuit function (returns early if condition not met)
For this to be sensible, map would have to be lazy evaluated. I believe this is the case, please do correct me if I am wrong.
I would be interested in doing the work for this assuming that the community considers it to be a useful addition to the Python core library.
Could I get some initial feedback on whether or not adding something like this would be considered useful?
I’m not totally sure exactly how it should be done. If a map_pairwise
was introduced, then why not higher-order versions which apply functions consisting of 3 arguments, or more?
I suppose one arguments against having a version which applies a trinary function, function of 4 arguments, etc, could be how to do the stride? For unary and binary it is obvious. Unary functions are applied to each element. A binary function is applied to every pair of elements. But then what do you do with a function which takes three arguments?