4

I'm using Python and I'm trying to figure out how to ascertain whether all numbers in a list are the same or different (even with just one integer being different) if beforehand I don't know the total number of elements in the list. Initially I wrote something like:

def equalOrNot(lst):
    if sum(lst)%len(lst)==0:
         return False
    else:
         return True

But it's not working in all cases. Any suggestions? Thanks

  • Check the duplicate post, your approach does not work for all case, for example `lst = [1,2,3]` – Alex Feb 02 '16 at 15:21
  • Your solution should fail when `sum(lst)` is multiple of `len(lst)` and all numbers are not equal. –  Feb 02 '16 at 15:54

4 Answers4

6

Use set:

if len(set(lst)) == 1: 
Kenly
  • 24,317
  • 7
  • 44
  • 60
1

Sure. You can use the builtin all()

all(numbers[0] == number for number in numbers)
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
0

Use this:

def equalOrNot(lst):
    for item in lst[1:]:
        if item != lst[0]:
            return False

    return True

Or just do:

lst[::-1] == sorted(lst)
0
if lst.count(lst[0]) == len(lst):

or

if lst.reverse() == lst.sort():
cromod
  • 1,721
  • 13
  • 26