How to check all elements of a list are same or different

Miles semanticist at gmail.com
Thu Apr 16 03:29:11 CEST 2009


On Wed, Apr 15, 2009 at 8:48 PM, Paul Rubin wrote:
> I'd use:
>
>   from operator import eq
>   all_the_same = reduce(eq, mylist)

That won't work for a sequence of more than two items, since after the
first reduction, the reduced value that you're comparing to is the
boolean result:

>>> reduce(eq, [0, 0, 0])
False
>>> reduce(eq, [0, 1, False])
True

I'd use:

# my preferred:
def all_same(iterable):
    it = iter(iterable)
    first = it.next()
    return all(x == first for x in it)

# or, for the pathologically anti-generator-expression crowd:
from functools import partial
from operator import eq
from itertools import imap
def all_same(iterable):
    it = iter(iterable)
    return all(imap(partial(eq, it.next()), it))

-Miles



More information about the Python-list mailing list