[Python-ideas] Add "equal" builtin function

Sjoerd Job Postmus sjoerdjob at sjoerdjob.com
Thu Oct 6 10:43:09 EDT 2016


On Thu, Oct 06, 2016 at 03:01:36PM +0100, Paul Moore wrote:
> On 6 October 2016 at 14:45, Filipp Bakanov <filipp at bakanov.su> wrote:
> > For now there are many usefull builtin functions like "any", "all", etc. I'd
> > like to propose a new builtin function "equal". It should accept iterable,
> > and return True if all items in iterable are the same or iterable is emty.
> > That's quite popular problem, there is a discussion of how to perform it on
> > stackoverflow
> > (http://stackoverflow.com/questions/3844801/check-if-all-elements-in-a-list-are-identical)
> > - all suggestions are either slow or not very elegant.
> > What do you think about it?
> 
> It's not a problem I've needed to solve often, if at all (in
> real-world code). But even if we assume it is worth having as a
> builtin, what would you propose as the implementation? The
> stackoverflow discussion highlights a lot of approaches, all with
> their own trade-offs. One problem with a builtin is that it would have
> to work on all iterables, which is likely to preclude a number of the
> faster solutions (which rely on the argument being an actual list).
> 
> It's an interesting optimisation problem, and the discussion gives
> some great insight into how to micro-optimise an operation like this,
> but I'd question whether it needs to be a language/stdlib feature.
> 
> Paul

I've needed it several times, but can't really remember what for
anymore, which makes me think it's not really that important.

A motivating reason for adding it to the builtins would be that it can
be written in C instead of Python, and hence be a lot faster. The single
slowest solution is actually the fastest when the difference is detected
very soon (case s3), all others are `O(n)` and not `O(first-mismatch)`.

Though, that means it could also be written in C and provided to PyPI,
at the cost of asking others to install an extra package.


More information about the Python-ideas mailing list