# Python Count Element Frequency and Proportion in List: A Beginner Guide

By | April 30, 2020

We often use python list to contain some elements, in order to analysis these elements, we often need to count their frequency and proportion. In this tutorial, we will illustrate python beginners how to do.

Create a python list

We should create a python list, which has contained some elements.

list_data = [1, 2, 4, 5, 2, 1, 4, 6, 7, 3, 2, 1]

Create function to count frequency and proportion

We will create a function called count_list_frequency_proportion to count frequency and proportion of a python list, here is an example code.

def count_list_frequency_proportion(list_data):
stat_frequency = {}
stat_proportion = {}
total = len(list_data)
for e in list_data:
if str(e) in stat_frequency:
stat_frequency[str(e)] += 1
else:
stat_frequency[str(e)] = 1
for key, value in stat_frequency.items():
stat_proportion[key] = value / total
return stat_frequency, stat_proportion

How to use this function?

You can use this function like this:

freq, proportion = count_list_frequency_proportion(list_data)
print(freq)
print(proportion)

Run this code, you will get this result.

{'1': 3, '2': 3, '4': 2, '5': 1, '6': 1, '7': 1, '3': 1}
{'1': 0.25, '2': 0.25, '4': 0.16666666666666666, '5': 0.08333333333333333, '6': 0.08333333333333333, '7': 0.08333333333333333, '3': 0.08333333333333333}