Counting in Python

Counting in Python happens commonly via the count() method.

For example, let’s count how many times the word “test” appears in a list:

words = ["test", "test", "not", "a", "test"]

n_test = words.count("test")

print(n_test)

Output:

3

To check how many times a letter occurs in a string, use the count() method of a string.

For example:

num_ls = "Hello world".count("l")

print(num_ls)

Output:

3

These are two common examples. In this guide, we are going to take a deeper look at counting in Python and see more example use cases.

How to Count Elements in a List in Python

Python list has a built-in method count(). It follows the syntax:

list.count(value)

This method loops through the list and counts how many elements are equal to the value.

For example, let’s count how many times the word “hi” occurs in a list:

words = ["hi", "hi", "hello", "bye"]

n_hi = words.count("hi")

print(n_hi)

Output:

2

How to Count Elements in a Tuple in Python

Python tuple has a built-in count() method. This works the same way as the count() method of a list.

tuple.count(value)

This method loops through the tuple and counts how many elements match the given value.

For example, let’s count how many times “hello” occurs in a tuple:

words = "hi", "hi", "hello", "bye"

n_hello = words.count("hello")

print(n_hello)

Output:

1

How to Count Substrings in a String

In Python, a string also has a count() method. You can use it to count how many times a character/substring occurs in a string.

The basic use case is similar to using the count() method of a list:

string.count(substring)

But the full syntax for the count() method of a string is:

string.count(substring, start_pos, end_pos)

Where:

  • substring is the string you want to find out the number of occurrences for.
  • start_pos is the index at which the search begins. This is an optional argument.
  • end_pos is the index at which the search stops. This is also an optional argument.

Let’s see how these parameters work.

substring

You can count the number of substring matches in a string using the count() method.

For example, let’s count many times the substring ‘is’ occurs in a given sentence:

num_is = "This test is simple".count("is")

print(num_is)

Output:

2

start_pos and end_pos

The start_pos determines from which index to start the substring search. The end_pos determines where to end the search.

For example, let’s count how many times “is” occurs, in a string but let’s ignore the first 5 characters by specifying start_pos 5.

Count but ignore first 5 letters.
num_is = "This test is simple".count("is", 5)

print(num_is)

Output:

1

The word “is” occurs twice in the full string. But the count() method returns 1 because we ignore the first 5 characters.

As another example, let’s count how many times the substring “is” occurs in a string again. This time let’s ignore the first 4 characters and the last 9. In other words, let’s set start_pos at 4 and end_pos at 9.

Count between 4th and 9th letters in Python
num_is = "This test is simple".count("is", 4, 9)

print(num_is)

Output:

0

Even though the word “is” occurs twice, we get 0 as a result because we only search between characters 4 and 9.

Next, let’s take a look at how to count occurrences in a dictionary.

How to Count the Number of Occurences in a Dictionary

A Python dictionary can only have one unique key. Thus, counting the number of specific keys is meaningless, as it is always 0 or 1.

But a dictionary can hold multiple identical values. To count the number of specific values in a dictionary:

  1. Get the values of a dictionary as a list.
  2. Call count() on the list.

You can get all the values of a dictionary with the values() method. This returns a view object. You can convert the view object to a list using the list() function.

For example, let’s count how many times a value of 5 occurs in a dictionary:

data = {
    "age": 5,
    "number_of_siblings": 3,
    "name": "Lisa",
    "address": "Imaginary street 7",
    "favorite_food": "Spaghetti",
    "favorite_number": 5
}

n_fives = list(data.values()).count(5)
print(n_fives)

Output:

2

Now you have learned how to use the count() method in Python to count occurrences in iterables in Python.

Last but not least, let’s go through 2 common tasks that involve counting in which you cannot use the count() method.

How to Count the Number of Files in a Directory in Python

To count the number of files in a directory, use the os module’s walk() method.

For example:

import os

path, dirs, files = next(os.walk("/Users/Jack/Desktop"))
num_files = len(files)

print(num_files)

How to Count the Number of Lines in a Text File in Python

To count the number of lines in a text file:

  1. Open the file.
  2. Read the file line by with the split() method.
  3. Count the number of lines resulting from the split.
# Remember to specify the correct path for the file.
file = open("example.txt","r")

# Split the file contents by new line into a list
content_list = file.read().split("\n")

# Loop through the lines and count how many there are
num_lines = 0
for i in content_list:
    if i:
        num_lines += 1

print(num_lines)

Conclusion

Today, you learned about counting in Python.

The count() method is a built-in utility for lists, tuples, and strings. It can be used to count how many times a specific item occurs in the sequence.

Thanks for reading. I hope you enjoy it.

Happy coding!

Further Reading

50 Python Interview Questions and Answers

50+ Buzzwords of Web Development