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
Counter(answers)builds a dictionary from each drink to its count.most_common()with no number returns every item, largest count first.- In the f-string,
:<8pads the text to 8 characters, aligned left.:>6aligns right in 6 characters, which keeps the numbers in a column. :.0%multiplies by 100 and adds a%sign, with no decimal places. So0.4prints as40%.'#' * countrepeats the#charactercounttimes, which gives a rough bar chart in the console.
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.