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

Paul Rubin http
Wed Apr 15 20:48:00 EDT 2009


John Posner <jjposner at snet.net> writes:
>   # 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]

I don't think you can rely on id's being the same if what
you want is that the values are the same:

    >>> a = "foo" + "bar"
    >>> b = "foobar"
    >>> a==b
    True
    >>> id(a) == id(b)
    False

I'd use:

   from operator import eq
   all_the_same = reduce(eq, mylist)

I don't see how to do all_different in less than quadratic time,
without using hashing or sorting:

  all_different = all(sum(1 for y in mylist if x==y)==1 for x in mylist)



More information about the Python-list mailing list