How to check all elements of a list are same or different
John Machin
sjmachin at lexicon.net
Wed Apr 15 20:33:33 EDT 2009
On Apr 16, 8:14 am, Chris Rebert <c... at rebertia.com> wrote:
> > On Wed, Apr 15, 2009 at 5:49 PM, Chris Rebert <c... at rebertia.com> wrote:
>
> >> On Wed, Apr 15, 2009 at 2:36 PM, Gaurav Moghe <moghe... at msu.edu> wrote:
> > Thanks for the reply. But I am interested in analysing the contents of just
> > one list. For example,
>
> > list1=[1,2,3,4,5,6]
> > So, the logical statement would probably be:
> > if list1==(contains all same values), print "Same" ---->False
> > if list1==(contains all different values), print "Different" ---->True
>
> > I wanted to know here whether there is a command/function that can do
> > exactly this. I hope I am more clearer than my last try!
@ OP: Not much ... what do you want to print if it contains *some*
different (but not all)?
> Ah, okay. Then you want:
>
> def all_same(lst):
> return len(set(lst)) == 1
>
> def all_different(lst):
> return len(set(lst)) == len(lst)
@ OP: These are very reasonable interpretations of "all same" and "all
different" but of course can both return False for the same input.
More information about the Python-list
mailing list