Open In App

Python – Index Frequency Alphabet List

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list we need to count the frequency of each alphabets from the list. For Example we have a list a = [‘a’, ‘b’, ‘a’, ‘c’, ‘b’, ‘a’] .The output should be having count of each alphabets = {‘a’:3, ‘b’:2 ,’c’:1 } . For finding frequency of each alphabet we can use dictionary, Counter class from collection library and list comprehension.

Using a Dictionary

We can iterate through the list and use a dictionary to store and count occurrences.

Python
a = ['a', 'b', 'a', 'c', 'b', 'a']
f = {}
for char in a:
    f[char] = f.get(char, 0) + 1
print(f)

Output
{'a': 3, 'b': 2, 'c': 1}

Explanation:

  • Code initializes an empty dictionary f and iterates through the list a. For each character in a, it uses the get() method to retrieve current count from f and adds 1 to it. If the character doesn’t exist in f, it defaults to 0.
  • After the loop f contains the count of occurrences for each character in a.

Using collections.Counter

Counter class from the collections module is designed to count frequencies in an iterable.

Python
from collections import Counter
a = ['a', 'b', 'a', 'c', 'b', 'a']
f = Counter(a)
print(f)

Output
Counter({'a': 3, 'b': 2, 'c': 1})

Explanation: Code imports the Counter class from the collections module and creates a Counter object f from the list a. This automatically counts the occurrences of each element in the list.

Using List Comprehension and count()

List comprehension can be used to iterate and count occurrences using the count() method.

Python
a = ['a', 'b', 'a', 'c', 'b', 'a']
f = [(char, a.count(char)) for char in set(a)]
print(f)

Output
[('a', 3), ('b', 2), ('c', 1)]

Explanation:

  • Code creates a list comprehension that iterates through the unique elements in the list a (using set(a) to eliminate duplicates). For each unique character, it counts its occurrences in a using the count() method.
  • Output f will be a list of tuples where each tuple contains a character from a and its corresponding count.


Next Article
Practice Tags :

Similar Reads