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

Scott David Daniels Scott.Daniels at Acm.Org
Wed Apr 15 19:15:13 EDT 2009


John Posner wrote:
> ...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]

Assuming you really are going for "is" comparison, how about:
     max(id(x) for x in mylist) == min(id(x) for x in mylist)

It has the advantage that if [id(x) for x in mylist] = [2N, 1N, 3N],
you get the answer you desire.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list