# How to Use the Python count() Method

09/16/2021

Contents

In this article, you will learn how to use the Python count() method.

## Python count() Method

The Python count() method is a built-in function that allows you to count the occurrences of a specific element within an iterable. The iterable can be a list, tuple, set, or string. Here’s how to use the count() method in Python:

##### Syntax
``iterable.count(element)``
##### Example
###### Counting elements in a list
``````fruits = ["apple", "banana", "apple", "cherry", "apple"]
count_apple = fruits.count("apple")
print(count_apple)   # Output: 3
``````

In the example above, we first created a list of fruits that contains three occurrences of the string “apple”. We then used the count() method to count the number of occurrences of “apple” in the list.

###### Counting characters in a string
``````string = "Hello, World!"
count_l = string.count("l")
print(count_l)   # Output: 3
``````

In this example, we created a string that contains three occurrences of the letter “l”. We then used the count() method to count the number of occurrences of “l” in the string.

###### Counting elements in a tuple
``````numbers = (1, 2, 3, 4, 5, 5, 5)
count_five = numbers.count(5)
print(count_five)   # Output: 3
``````

In this example, we created a tuple that contains three occurrences of the number 5. We then used the count() method to count the number of occurrences of 5 in the tuple.

###### Counting elements in a set
``````my_set = {1, 2, 3, 4, 4, 4}
count_four = my_set.count(4)
print(count_four)   # Output: AttributeError: 'set' object has no attribute 'count'
``````

In this example, we created a set that contains three occurrences of the number 4. We then used the count() method to count the number of occurrences of 4 in the set. However, the count() method is not available for sets. You can convert the set into a list or tuple and then use the count() method as shown in the previous examples.