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

John Posner jjposner at snet.net
Wed Apr 15 18:56:45 EDT 2009


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]




More information about the Python-list mailing list