Skip to main content

How to find the frequency of each element in a list in Python

How to find the frequency of each element in a list in Python.

Here is a step-by-step tutorial on how to find the frequency of each element in a list using Python:

Step 1: Create a list

Start by creating a list of elements for which you want to find the frequency. For example, let's create a list of numbers:

numbers = [1, 2, 3, 4, 1, 2, 3, 1, 2, 1]

Step 2: Initialize an empty dictionary

Next, initialize an empty dictionary to store the frequency of each element. The keys of the dictionary will be the elements from the list, and the values will be their corresponding frequencies.

frequency = {}

Step 3: Iterate over the list

Loop through each element in the list and update the frequency dictionary accordingly. For each element, check if it already exists as a key in the dictionary. If it does, increment the corresponding value by 1. If it doesn't, add a new key-value pair with the element as the key and 1 as the initial value.

for element in numbers:
if element in frequency:
frequency[element] += 1
else:
frequency[element] = 1

Alternatively, you can use the get() method to achieve the same result in a more concise way:

for element in numbers:
frequency[element] = frequency.get(element, 0) + 1

Step 4: Print the frequency of each element

Finally, you can print the frequency of each element in a readable format. You can iterate over the keys of the frequency dictionary and print the key-value pairs.

for key, value in frequency.items():
print(f"The frequency of element {key} is {value}")

Alternatively, if you want to store the frequencies in a new list, you can use a list comprehension:

frequencies = [f"The frequency of element {key} is {value}" for key, value in frequency.items()]
print(frequencies)

That's it! You have successfully found the frequency of each element in a list using Python.