Create a function with a list parameter. Return a dictionary of the list items and their counts.
def count_items(lst):
""" Return counts of the list items. """
counts = {item: lst.count(item) for item in lst}
return counts
Now, call the function with a list and print its items and their counts in two columns, like so:
lst = ['abc', 'cde', 'abc', 'fgh', 'ijk', 'cde', 'abc', 'ijk']
print("{0: <15} {1}".format("Input", "Output")) # adjust column width as needed
for key, value in count_items(lst).items():
print("{0: <17} {1}".format(key, value))
It prints:
Input Output
abc 3
cde 2
fgh 1
ijk 2
If you've lists that are quite big, the code below is more efficient:
from collections import Counter
def count_items(lst):
""" Return counts of the list items. """
return Counter(lst)
lst = ['abc', 'cde', 'abc', 'fgh', 'ijk', 'cde', 'abc', 'ijk']
print("{0: <15} {1}".format("Input", "Output")) # adjust column width as needed
for key, value in count_items(lst).items():
print("{0: <17} {1}".format(key, value))