Python Program to Count the Frequency of Each Element in a List
Beginner · Lists
The frequency of an element is the number of times it appears in a list. This program counts every element at once by keeping a dictionary in which each value is a key and its count is the value.
Program
frequency_of_list_elements.py
fruits = ["apple", "mango", "apple", "banana", "mango", "apple", "kiwi"]
frequency = {}
for fruit in fruits:
if fruit in frequency:
frequency[fruit] += 1 # seen before: add one to its count
else:
frequency[fruit] = 1 # first time: start its count at 1
print("List:", fruits)
print("Frequency of each element:")
for fruit, count in frequency.items():
print(f" {fruit:<7} {count}")
Output
List: ['apple', 'mango', 'apple', 'banana', 'mango', 'apple', 'kiwi'] Frequency of each element: apple 3 mango 2 banana 1 kiwi 1
How it works
- The dictionary
frequencystarts empty. - For each fruit, the program checks whether it is already a key: if so its count goes up by 1, and if not it is added with a count of 1.
- Dictionaries remember the order keys were added, so the fruits print in the order they first appear.
frequency.items()gives each key and value together, and{fruit:<7}lines the counts up in a column.
Other ways to write it
Using Counter
Using Counter
from collections import Counter
numbers = [3, 1, 3, 2, 1, 3, 4]
counts = Counter(numbers)
print("Frequencies:", dict(counts))
value, count = counts.most_common(1)[0]
print("Most frequent:", value, "appears", count, "times")
Output
Frequencies: {3: 3, 1: 2, 2: 1, 4: 1}
Most frequent: 3 appears 3 timesCounter does the counting in one line, and most_common() returns the values from the most to the least frequent.
Using dict.get()
Using dict.get()
fruits = ["apple", "mango", "apple", "banana", "mango", "apple", "kiwi"]
frequency = {}
for fruit in fruits:
frequency[fruit] = frequency.get(fruit, 0) + 1
print("Frequencies:", frequency)
Output
Frequencies: {'apple': 3, 'mango': 2, 'banana': 1, 'kiwi': 1}get(fruit, 0) returns the current count, or 0 for a new fruit, so the if and else collapse into one line.
Try it yourself
Change the program to print only the fruits that appear more than once.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count the Frequency of Each Character in a String
- Count the Frequency of Words in a String
- Count Occurrences of an Element in a List
- Find Duplicates in a List
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- Remove Duplicates from a List
- a Menu-Driven List
- Find the Sum of Elements in a List
All Python programs · CBSE class 12 practical file · Python exercises