
👉Python count() Method: Complete Guide with Examples
The count() method in Python is a built-in function that returns the total number of occurrences of a specified element in a list or string. This method is highly useful when you need to count duplicates or specific values in your data.
👉Table of Contents
- What is Python count()?
- Python count() Syntax
- Parameters and Return Value
- Examples of Using count() in Python
- Example 1: Counting String Elements in a List
- Example 2: Counting Duplicate Numbers in a List
- Summary
👉What is Python count()?
The count() method is a Python built-in function used to count how many times a specific element appears in a list or string.
👉Python count() Syntax
python
list.count(element)
👉Parameters
- element: The element you want to count in the list.
👉Return Value
- The method returns an integer value representing the count of the specified element.
- If the element is not found, the method returns 0.
👉Examples of Using count() in Python
👉Example 1: Counting String Elements in a List
In this example, we will count how many times the word “green” appears in the list.
Code Example:
python
list1 = [‘red’, ‘green’, ‘blue’, ‘orange’, ‘green’, ‘gray’, ‘green’]
color_count = list1.count(‘green’)
print(‘The count of color: green is’, color_count)
Output:
csharp
The count of color: green is 3
👉Example 2: Counting Duplicate Numbers in a List
In this example, we will count the number of times the number 3 appears in the list.
Code Example:
python
list1 = [2, 3, 4, 3, 10, 3, 5, 6, 3]
elm_count = list1.count(3)
print(‘The count of element: 3 is’, elm_count)
Output:
csharp
The count of element: 3 is 4
👉Summary
✅ The count() method is a powerful tool in Python for counting elements in lists or strings.
✅ It requires the element to be specified and returns an integer value representing the count.
✅ If the element is not found, the method returns 0.