ByteBoard Notes Notes

Count the frequency of each element in a list

Computer Science XI · Experiment 22 of 27 · Python

11-CSPython programs
Expt. No.22
Page No.44

Frequency of elements

Aim

To write a Python program that counts how many times each element occurs in a list and in a tuple.

Concepts used

Algorithm

  1. Input the elements into a list.
  2. Keep a second list of elements already reported.
  3. For each element not yet reported, display it with count() and add it to the reported list.
  4. Convert the list to a tuple and display the count of one chosen element with the tuple's count().

Program

# Frequency of each element in a list (and a tuple) lst = []n = int(input("How many elements? "))for i in range(n):    lst.append(int(input("Enter element: ")))print("List:", lst) done = []for x in lst:    if x not in done:        print(x, "occurs", lst.count(x), "time(s)")        done.append(x) t = tuple(lst)x = int(input("Element to count in the tuple: "))print(x, "occurs", t.count(x), "time(s) in the tuple")

A marked line continues the line above it. In your file, write it on the same line.

Output

$ python frequency_of_elements.py
How many elements? 8 Enter element: 3 Enter element: 5 Enter element: 3 Enter element: 7 Enter element: 5 Enter element: 3 Enter element: 9 Enter element: 7 List: [3, 5, 3, 7, 5, 3, 9, 7] 3 occurs 3 time(s) 5 occurs 2 time(s) 7 occurs 2 time(s) 9 occurs 1 time(s) Element to count in the tuple: 5 5 occurs 2 time(s) in the tuple

✓ Printed by running this program, not typed by hand.

Result

In [3, 5, 3, 7, 5, 3, 9, 7], 3 occurred 3 times, 5 and 7 twice each, and 9 once; each value was reported once. The tuple's count() also gave 2 for 5.

Viva voce: what the examiner may ask

01Why is the done list needed?

Without it, 3 would be reported three times, once for each time it appears.

02What does count() return for a value that is not in the list?

0. It does not raise an error.

03Which methods do lists and tuples share?

count() and index(), plus functions such as len(), max(), min() and sum().

Variations for the lab test

  1. Display only the elements that occur more than once.
  2. Find the element that occurs most often.
  3. Do the same task with a dictionary (see the next experiment).
! Common mistake Removing items from the list while looping over it skips elements and gives wrong counts.
Back to the 11-CS index