How to count occurrences of a character in a Python list

In this Python tutorial, I will show you how to count occurrences of a character in a Python list, with different methods using demonstrative examples.

Lists in Python are very versatile. They can contain any type of object as many times as we wish. They can also contain the same objects as many times as we want. And, we can count how many times they appear in the Python list or even a character present in the Python list.

For example, Here’s an example of what a Python list looks like with the same elements:

People_cities = ['AK', 'CO', 'NY', 'NJ', 'CA', 'TX', 'CA', 'NY', 'NY', 'TX']
How to count occurrences of the character in a Python list.

In this scenario, there are people in a conference hall from different cities(written in shortcuts) in the USA. We need to find the number of people who came from ‘NY'(New York).

We have many different ways to find out the occurrence of the ‘NY’ in the list.

Counting occurrences of a character in a Python list

There are many different ways to count the occurrence of a character in a List in Python. They are:

  • The Pythonic count() Method
  • Using List Comprehension
  • Using for Loop
  • Using Counter class from collections module
  • Using filter Function
  • Using Dictionary
  • Using Regular Expressions
READ:  Python program for bubble sort [3 methods]

We will see them one by one using illustrative examples.

The count() method to count occurrence of a character in a Python list

Python’s built-in count() function can be used to count the occurrence of an element in a list.

For instance, let’s consider a Python list of popular American fast-food chains.

fast_food_chains = ['McDonald\'s', 'Starbucks', 'Subway', 'Taco Bell', 'Subway', 'Burger King', 'Starbucks']

# Count the occurrence of 'Starbucks'
count = fast_food_chains.count('Starbucks')

print('The number of times Starbucks present is:', count)

The Output is:

The number of times Starbucks present is: 2
How to count occurrences of the character in a Python list using count() method

This way we can count the occurrence of the element in a Python list using the count() function.

Use List comprehension to count occurrences of a character in the Python list

List comprehension is a Pythonic way to perform operations on lists. We can use it to count occurrences as well.

Let’s take an example of counting how many times the character ‘a’ appears in a Python list of U.S. Presidents:

presidents = ['George Washington', 'Thomas Jefferson', 'Abraham Lincoln', 'Franklin D. Roosevelt', 'Barack Obama']

# Count the occurrence of 'a'
count = sum([president.count('a') for president in presidents])

print('Total number of \'a\' present in the list is: ', count)

The Output is:

Total number of 'a' present in the list is:  9
How to count occurrences of the character in a Python list using list comp

This way we can use list comprehension to count the occurrences of a character in a Python list.

Counting occurrences of an element in the List of Python using for loop

A simple for loop in Python can be used to traverse the list and count occurrences:

For example, we have a list of cities in the USA: let’s count the number of times ‘Los Angeles’ occur in the Python list.

Here, we will first define the Python list which will contain the names of the cities. Then we will initialize a variable count to 0. This variable is used to keep track of the number of times ‘Los Angeles’ occurs in the Python list.

cities = ['Los Angeles', 'New York', 'Los Angeles', 'Chicago', 'Los Angeles', 'Houston', 'Phoenix']

# Count the occurrence of 'Los Angeles'
count = 0
for city in cities:
    if city == 'Los Angeles':
        count += 1

print('Number of times Los Angeles occur is:', count)

The output is:

 Number of times Los Angeles occur is: 3
How to count occurrences of the character in a Python list using for loop

This way we can use for loop to count the occurrences of the element in a Python list.

READ:  How to read a CSV file in Python 

Using the Counter Class from the Collections Module to count the occurrence of the item in a Python list

Python’s collections module offers the Counter class, which makes it a breeze to count items in a list.

For instance, let’s take a Python list to count the occurrences of different basketball teams in a list of NBA Champions over the years.

nba_champions = ['Lakers', 'Bulls', 'Celtics', 'Spurs', 'Warriors', 'Bulls', 'Lakers', 'Celtics']

# Import the Counter class
from collections import Counter

# Create a Counter object
counter = Counter(nba_champions)

# Count the occurrence of 'Lakers'
print('The number of times Lakers being a nba champion: ',counter['Lakers'])

The output is:

The number of times Lakers being a nba champion:  2
How to count occurrences of the character in a Python list using counter from collection

This way we can use the counter class from the collections module in Python to count the occurrence of the element in the List.

Counting the occurrence of the character in the list of Python using filter function

The filter() function in Python, filters the given sequence(list) with the help of a function(lambda function) that tests each element in the sequence to be true or not.

For example, we’re given a Python list of tech companies we visited this month, and we want to count the number of times ‘Apple’ appears in the list. Here’s the code:

tech_companies = ['Apple', 'Microsoft', 'Google', 'Facebook', 'Amazon', 'Apple', 'Netflix']

Apple = len(list(filter(lambda x: x == 'Apple', tech_companies)))

print('Number of times we visited Apple company is: ',Apple)

The output is:

Number of times we visited Apple company is:  2
How to count occurrences of the character in a Python list using filter method

This way we can use the filter function to count the occurrence of the characters in a Python list.

Use Dictionary to count occurrences of elements in the Python list

We can also use a Python dictionary to count the occurrences of items in a list.

READ:  How to Take Continuous Input in Python?

Suppose we have a Python list of American car manufacturers and we want to count the number of each manufacturer present in the list are:

manufacturers = ['Ford', 'General Motors', 'Tesla', 'Rivian', 'Lordstown Motors']

count = {}

for manufacture in manufacturers:
    if manufacture in count:
        count[manufacture] += 1
    else:
        count[manufacture] = 1

print(count)

The output is:

{'Ford': 1, 'General Motors': 1, 'Tesla': 1, 'Rivian': 1, 'Lordstown Motors': 1}
How to count occurrences of the character in a Python list using dictionary

This way we can use the dictionary to count each element occurrence in the list of Python.

Use Regular expressions to count the occurrence of the character in the Python list

Regular expressions, also known as regex in Python, are sequences of characters that form a search pattern. Regex can be used in Python through the re module. They can be particularly helpful in situations like counting occurrences of a character or a pattern in a list of strings.

Let’s consider a Python list of famous American athletes, and we want to find how many times ‘Jordan’ appears:

import re

athletes = ['Michael Jordan', 'LeBron James', 'Tom Brady', 'Michael Jordan', 'Serena Williams', 'Tiger Woods', 'Jordan Spieth']

# Join the list into a single string
athletes_string = ' '.join(athletes)

# Count the occurrence of 'Jordan'
count = len(re.findall('Jordan', athletes_string))

print('Number of times Jordan present the list is:', count)

The output is:

Number of times Jordan present the list is: 3
How to count occurrences of the character in a Python list using regular expression

This way we use Regular expression to count the occurrence of the characters in the Python list.

Conclusion

Python offers a variety of techniques for counting occurrences of a character or element in a list. These methods range from straightforward techniques like using a for loop to employing built-in Python functions such as count() and filter() or using data structures like dictionaries, list comprehension, or by using a regular expression, and counter from the collections module.

You may also like to read: