On 6 October 2016 at 23:45, Filipp Bakanov <fil...@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.

If the items are hashable, you can already just dump them in a set:

    len(set(iterable)) <= 1

If they're not hashable or you want to exit ASAP on larger inputs,
you'll want an algorithm that works the same way any/all do:

    def all_same(iterable):
        itr = itr(iterable)
        try:
            first = next(itr)
        except StopIteration:
            return True
        return all(x == first for x in itr)

(Checking the SO question, both of those are given in the first answer)

If you know you have a sequence, you can also do:

    not seq or all(x == seq[0] for x in seq)

Exactly which of those options makes sense is going to depend on what
format your data is in, and what other operations you're planning to
do with it - without a context of use in the SO question, it sounds
more like someone seeking help with their algorithms and data
structures homework than it does a practical programming problem.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to