PythonMastery

Frequency table from a list in Python

Count each item in a list with collections.Counter and print a frequency table with counts, percentages and a small text bar chart.

A frequency table lists each distinct value and how many times it appears. collections.Counter does the counting, and f-strings line up the columns.

The program

python
from collections import Counter

answers = ["tea", "coffee", "tea", "water", "coffee", "tea", "juice", "tea", "coffee", "water"]

table = Counter(answers)
total = len(answers)

print(f"{'Drink':<8}{'Count':>6}{'Share':>8}")
for drink, count in table.most_common():
    share = count / total
    print(f"{drink:<8}{count:>6}{share:>8.0%}  {'#' * count}")
output
Drink    Count   Share
tea          4     40%  ####
coffee       3     30%  ###
water        2     20%  ##
juice        1     10%  #

How it works

Numbers in order of value

For numbers, such as dice rolls, a table sorted by the value is often easier to read than one sorted by count:

python
from collections import Counter

rolls = [3, 6, 1, 3, 4, 6, 6, 2, 3, 5, 6, 1]

table = Counter(rolls)
for value in sorted(table):
    print(value, table[value])
output
1 2
2 1
3 3
4 1
5 1
6 4

sorted(table) sorts the keys of the Counter, which are the dice values.

Related programs: Count occurrences of an element in a list.

Learn the idea: collections: The Stdlib's Hidden Power, F-Strings: Modern String Formatting

A longer explanation: Count anything with collections.Counter