How to Obtain the Mode of a List in Python

The mathematical mode is the value in a data set that occurs most often. You want to find the mode if you are checking for duplicate results. The brevity that the Python language allows can make the solution both elegant and minimal.

Instructions

    • 1

      Open a new file in a text editor.

    • 2

      Type in the following lines. This sets up the list you want to calculate the mode of, as well as the result variables and a dictionary for sorting.

      l = (1,2,3,4,5,6,7,8,7,7,45,7,1,3,3)
      d = {}
      mode = 0
      freq = 0

    • 3

      Enter the following lines into your editor and press the "Tab" key any time you see <tab>:

      for i in l:
      <tab>if d.has_key(i):
      <tab><tab>d[i] += 1
      <tab>else:
      <tab><tab>d[i] = 1

    • 4

      Add the next lines to your file, replacing <tab> with the "Tab" key as you go:

      <tab>if d[i] > freq:
      <tab><tab>mode = i
      <tab><tab>freq = d[i]

    • 5

      Put the next line at the bottom of your file:

      print "Found mode", mode, "frequency", freq

    • 6

      Run the program to see the result. It prints "Found mode 7 frequency 4."

Tips & Warnings

  • Indentation matters. Whether you use spaces or tabs in your Python code, you must be consistent. Pick one and stick with it.

Related Searches:

Comments

Related Ads

Featured