# Python – Fractional Frequency of elements in List

• Last Updated : 21 Jun, 2022

Given a List, get fractional frequency of each element at each position.

Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 4]
Output : [‘1/4’, ‘1/3’, ‘2/4’, ‘1/1’, ‘1/1’, ‘2/3’, ‘3/4’, ‘3/3’, ‘4/4’]
Explanation : 4 occurs 1/4th of total occurrences till 1st index, and so on.
Input : test_list = [4, 5, 4, 6, 7, 5]
Output : [‘1/2’, ‘1/2’, ‘2/2’, ‘1/1’, ‘1/1’, ‘2/2’]
Explanation : 4 occurs 1/2th of total occurrences till 1st index, and so on.

Method : Using Counter() + loop + dictionary comprehension

In this, we use Counter() to get the frequency of each element in list and to form denominator part of fraction. Numerator is initialized to 0 for each element. Then loop is used to add the elements in numerator and join with total frequency in denominator.

## Python3

 # Python3 code to demonstrate working of# Fractional Frequency of elements in List# Using Counter() + loop + dictionary comprehensionfrom collections import Counter # initializing listtest_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6] # printing original listprint("The original list is : " + str(test_list)) # initializing numeratornumber = {idx : 0 for idx in set(test_list)} # initializing denominatordenom = Counter(test_list) res = []for ele in test_list:         # increasing counter    number[ele] += 1    res.append(str(number[ele]) + '/' + str(denom[ele])) # printing resultprint("Fractional Frequency List : " + str(res))

Output

The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6]
Fractional Frequency List : ['1/5', '1/3', '2/5', '1/3', '1/1', '2/3', '3/5', '3/3', '4/5', '2/3', '5/5', '3/3']

My Personal Notes arrow_drop_up