How to count in Python
Counting in Python is a simple operation, made more efficient with the introduction of collections.Counter. Whether you want to count the occurrences of a substring in a string, number of unique words in a sentence, or simply want to know the 3 most frequently occurring strings in a list, it’s all possible with just a few lines of code.
This guide takes an in-depth look at the different solutions available, complete with documented code samples.
Simple count
string.count()The string.count() method returns the number of times a specified string appears in another string. Optional parameters can be supplied for the start and end point of the search in the main string for the substring.
Syntax: string.count(substring, start=…, end=…)
# Create a test string
my_string = "This is a test string."
print("my_string =", my_string)
# Count how many times 't' appears in my_string
print("Times 't' appears in my_string =", my_string.count("t"))
# Count how many times 'is' appears in my_string
print("Times 'is' appears in my_string =", my_string.count("is"))
# Count how many times 'is' appears in my_string, with start at 0 and end at 6
print("Times 'is' appears in my_string(0,6) =", my_string.count("is",0,6))
Output:
my_string = "This is a test string."
Times 't' appears in my_string = 3
Times 'is' appears in my_string = 2
Times 'is' appears in my_string(0,6) = 1
list.count()
The list.count() method returns the number of times a specified item appears in the list. The method accepts 1 argument, with no optional parameters for the start and end index within which to search.
Syntax: list.count(element)
# Create a test list
my_list = ["T","e","s","t","","l","i","s","t"]
print("my_list = ", my_list)
# Count how many times 't' appears in my_list
print("Times 't' appears in my_list =", my_list.count("t"))
# Count how many times 'T' appears in my_list
print("Times 't' appears in my_list =", my_list.count("T"))
Output:
my_list = ["T","e","s","t","","l","i","s","t"]
Times 't' appears in my_list = 2
Times 'T' appears in my_list = 1
Notice how when we applied count("t") to our string, we had a result of 3 occurences, but when we applied the same to our list, we only had 2 occurences. This is because counting in a list is case sensitive, whereas string counts are case insensitive.
Important: Calling count in a loop will pass over the list once per count call. A more efficient way to count multiple items would be to use Counter from the collections module.
Get 3 most common strings from a list
Return the 3 most common strings and their counts from a list.
from collections import Counter
my_list = ["a","a", "b", "b", "b", "c", "c", "d", ""]
my_dict = Counter(my_list)
# Find 3 most frequently occurring strings
top3 = my_dict.most_common(3)
# Display initial list
print("Initial List:")
print(my_list, "\n")
# Display initial dictionary
print("Initial Dictionary:")
print(my_dict, "\n")
# Display 3 most common values
print("3 most common strings are:")
print("Keys: Values")
for i in top3:
print(i[0]," :",i[1])
Output:
Initial List:
["a","a", "b", "b", "b", "c", "c", "d", ""]
Initial Dictionary:
Counter({'b': 3, 'a': 2, 'c': 2, 'd': 1})
3 most common letters are:
Keys: Values
b : 3
a : 2
c : 2
Count number of unique letters
There are multiple ways to achieve a count of distinct items. Two of the most popular solutions are:
- Using
collections.Counter - Pass the words into a
set(), then check the length of the set
from collections import Counter
# METHOD 1: Create a sample list of strings, then count the keys() and values()
my_letters = ["a","a", "b", "b", "b", "c", "c", "d", ""]
print("my_letters =", my_letters)
print("Unique letters =", Counter(my_letters).keys()) # equals to list(set(my_letters))
print("Count of letter occurences =", Counter(my_letters).values()) # counts the elements' frequency
# METHOD 2: Pass the iterable to a set
my_letters = ["a","a", "b", "b", "b", "c", "c", "d", ""]
print("Number of unique letters in my_letters =", len(set(my_letters)))
Output:
my_letters = ["a","a", "b", "b", "b", "c", "c", "d", ""]
Unique letters = dict_keys(['a', 'b', 'c', 'd', ''])
Count of letter occurences = dict_values([2, 3, 2, 1, 1])
Number of unique letters in my_letters = 5