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

Rhodri James rhodri at wildebst.demon.co.uk
Wed Apr 15 19:13:52 EDT 2009


On Wed, 15 Apr 2009 23:56:45 +0100, John Posner <jjposner at snet.net> wrote:

> Chris Rebert wrote:
>> Ah, okay. Then you want:
>>
>> def all_same(lst):
>>     return len(set(lst)) == 1
>>
>> def all_different(lst):
>>     return len(set(lst)) == len(lst)
>>
>> Note that these require all the elements of the list to be hashable.
>>
> This solution relies on the object ID -- no hashability required:
>
>   # get list of object-IDs
>   ids = map(lambda x: id(x), mylist)
>   # ALL THE SAME? ... test whether "average ID" matches "first ID"
>   sum(ids)/len(ids) == ids[0]

Oh John!  After all the recent discussion of identity versus equality too.

>>> my_list = [ 1024 ]
>>> my_list.append(1024) # Defeat the interpreter's cunningness
>>> ids = map(lambda x: id(x), ml)
>>> ids
[9864656, 9864704]
>>> sum(ids)/len(ids) == ids[0]
False


-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list