How to error check Python Statistics mode function?

10,358

According to the documentation, If data is empty, or if there is not exactly one most common value, StatisticsError is raised. Thus, simply having duplicates in the list will not ensure that there is a mode.

A preferred solution would be to use the exception mechanism, e.g.:

nums = [1,2,3,4,5,5,6,7,7,8,9]
try:
    m = mode(nums)
except StatisticsError:
    print ("No unique mode found")
Share:
10,358
Bennett
Author by

Bennett

Updated on June 04, 2022

Comments

  • Bennett
    Bennett almost 2 years

    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.

  • Padraic Cunningham
    Padraic Cunningham almost 10 years
    I changed the logic, I thought you wanted to not run the Mode function if there were dups, now it will only run it there are dups and ignore otherwise
  • whereswalden
    whereswalden almost 10 years
    Using a try-except block is the proper way to deal with potential malformed data errors and is also more performant assuming errors are infrequent. Ask for forgiveness, not permission.
  • whereswalden
    whereswalden almost 10 years
    Whoops, because the OP preceded the parens with a space, I thought they were using the print keyword. That explains how it worked in Python 3.
  • whereswalden
    whereswalden almost 10 years
    Probably none, but it means you iterate over the entire list and duplicate at least part if it in memory every time that code is executed. Why do all that when statistics.mode will tell you if there's a problem anyways? Better to just let it do the work and handle the error case.