Search code snippets, questions, articles...

Get count of a specific element in a list using Python

We can use the count() function of the Python list to get the count of a specific element in the list.
# Define a list
numbers = [4, 4, 5, 9, 4, 3, 6, 9]

# Get the frequency of 4
result = numbers.count(4)

# Print the result
print(result)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

3

In the code snippet

  1. We have created a list called numbers that contains multiple items.
  2. We are using the count() function of the list and getting the frequency of 4 in the numbers list and assigning them to the result named variable.
  3. Printing the result.

List.count() function

As we have already explained the functionality of List.count() function in Python. The count() function returns the count of a specific item in the list.

Syntax

List.count(item)

Code Example

my_list = ['a', 'b', 'a', 'c', 'd', 'a', 'a']

result = my_list.count('a')

print(result)

Output

4
Was this helpful?
0 Comments