count() method is used to find how many times a specific element appears in a list. It searches the entire list and returns the total number of matching occurrences as an integer.
Example: In this example, count() is used to find how many times a number appears in a list.
a = [1, 2, 3, 1, 2, 1, 4]
c = a.count(1)
print(c)
Output
3
Explanation: a.count(1) counts all occurrences of 1 in the list and since 1 appears three times, the method returns 3.
Syntax
list.count(value)
- Parameters: value - The element whose occurrences need to be counted.
- Return Value: Returns an integer representing the number of occurrences of the specified element.
Examples
Example 1: In this example, count() is used to determine how many times a particular value appears in a list containing repeated elements.
a = [10, 20, 10, 30, 10, 40]
c = a.count(10)
print(c)
Output
3
Explanation:
- a.count(10) counts every occurrence of 10 in the list.
- The value 10 appears three times, so the result is 3.
Example 2: In this example, a nested list is counted as a single element. The method checks for exact matches of the sublist.
a = [[1, 2], [3, 4], [1, 2], [5, 6]]
c = a.count([1, 2])
print(c)
Output
2
Explanation:
- a.count([1, 2]) searches for the exact sublist [1, 2].
- The sublist appears twice in the list, so 2 is returned.
Example 3: In this example, a sentence is converted into a list of words and count() is used to find the frequency of a specific word.
w = "python is simple and python is powerful".split()
c = w.count("python")
print(c)
Output
2
Explanation:
- .split() converts the sentence into a list of words.
- w.count("python") counts how many times "python" appears in the list.
- The word appears twice, so the result is 2.