-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
  • 15,954
  • 55
  • 201
  • 355

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
  • 57,957
  • 11
  • 121
  • 147