Use count() Function in Python with Example

The `count()` function in Python is used in different contexts depending on whether you are working with a list, tuple, string, or other iterable. It is used to count the number of occurrences of a specific element in the iterable.

Syntax

For a list, tuple, or string:

iterable.count(value)

– iterable: The list, tuple, or string where you want to count occurrences.
– value: The element or substring whose count you want to find.

Example with a List

# Example list
fruits = ["apple", "banana", "cherry", "apple", "banana", "apple"]
# Count the number of times 'apple' appears in the list
apple_count = fruits.count("apple")
print("The word 'apple' appears:", apple_count, "times")

Output

The word 'apple' appears: 3 times

Example with a Tuple

# Example tuple
numbers = (1, 2, 3, 4, 1, 2, 1)
# Count the number of times '1' appears in the tuple
count_of_one = numbers.count(1)
print("The number 1 appears:", count_of_one, "times")

Output

The number 1 appears: 3 times

Example with a String

# Example string
text = "hello world, hello universe"

# Count the number of times 'hello' appears in the string
hello_count = text.count("hello")
print("The word 'hello' appears:", hello_count, "times")

Output

The word 'hello' appears: 2 times

Explanation

– Lists and Tuples: `count()` returns the number of times a specified element appears.
– Strings: `count()` returns the number of times a specified substring appears. The search is case-sensitive, so `”Hello”` and `”hello”` would be counted separately.

The `count()` function is useful for determining how often a particular element or substring appears in a list, tuple, or string.