Search code examples
pythonmode

How to error check Python Statistics mode function?


There is a question similar to this existing but does not quite fit my situation. I'm using Python 3.4 and want to use the mode function of the statistics module, however when there is not a mode python terminates program and gives me an error. Is there an if statement I could write to check if there are duplicates in my list, and if not display a print message before the mode function begins, and prevent the mode function from running?
So far I have:

    UserNumbers=input("Enter number sequence separated by spaces: ")
    nums = [int(i) for i in UserNumbers.split()]
    Average = mean(nums)
    print ("The mean is ", Average)
    Middle = median(nums)
    print ("The median is ", Middle)
    Most = mode(nums)
    print ("The mode is ", Most)

I am a beginner so it's a bit hard to convey my problem properly, please excuse incorrect terminology.


Solution

  • Check with a set:

    if len(set(nums)) == len(nums) 
    

    If you have dups the length of the set will be shorter than the length of your list.

    if len(set(nums)) != len(nums): # check different lengths, if different we have dups 
        print ("The mode is ", Most)
        Most = mode(nums)
    else:      # else both are the  same size so no dups, just print 
        print("No duplicates in nums") 
    

    Set cannot have duplicate items:

    In [1]: nums =[1,2,3,4,1]
    
    In [2]: nums
    Out[2]: [1, 2, 3, 4, 1]
    
    In [3]: set(nums)
    Out[3]: {1, 2, 3, 4} # sets cannot have duplicate items
    
    In [4]: len(set(nums)) == len(nums) # set = len 4, nums = len 5
    Out[4]: False