-1

I want to be able to get True if all the list's items are the same:

For example checking this list would return True:

myList = [1,1,1,1,1,1,1] 

While checking this list would result to False:

myList = [2,2,2,2,2,2,1] 

What would be a shortest solution without a need to declare any new variables?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392

1 Answers1

4

Using set would drop duplicates. Then you can chcek the length, to get the number of different values.

len(set(myList)) <= 1

This works if the values are hashable.

However, if you expect to run this on long lists and expect a negative answer often, short circuiting might prove faster:

def is_unique(myList):
   seen = set()
   for x in myList:
       seen.add(x)
       if len(seen) > 1:
          return False
   return True
shx2
  • 61,779
  • 13
  • 130
  • 153