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

Arnaud Delobelle arnodel at googlemail.com
Thu Apr 16 05:57:43 EDT 2009


Piet van Oostrum <piet at cs.uu.nl> writes:

>>>>>> John Machin <sjmachin at lexicon.net> (JM) wrote:
>
>>JM> On Apr 16, 8:14 am, Chris Rebert <c... at rebertia.com> wrote:
>>>> 
>>>> def all_same(lst):
>>>>     return len(set(lst)) == 1
>>>> 
>>>> def all_different(lst):
>>>>     return len(set(lst)) == len(lst)
>
>>JM> @ OP: These are very reasonable interpretations of "all same" and "all
>>JM> different" but of course can both return False for the same input.
>
> They can even both return True for the same input!

I didn't see the simple:

>>> def all_same(l):
...     return all(l[i]==l[i+1] for i in range(len(l)-1))
... 
>>> all_same([1,2,3])
False
>>> all_same([1])
True
>>> all_same([1,1,1])
True
>>> all_same([1,1,1,2])
False
>>> all_same([])
True
>>> 

-- 
Arnaud



More information about the Python-list mailing list