Note
Python - count() - Count occurrences of an element in a collection
How to count elements in iterable - Python function count() with examples
iterable.count(value, start=None, end=None) is a built-in function that returns the count number of elements in your object.
It can be called on the following data structures - list,
tuple, string, byte, bytearray, and range objects.
The count() function requires value argument that specifies what are we looking for and on some objects
we can also provide indexes between which we want to count elements.
Parameters:
-
value: The element to count within the iterable. -
start(optional): The starting index of the range to count -int. Default is0. -
end(optional): The ending index (exclusive) of the range to count -int. Default is the length of the iterable.
Take a look at the examples below:
Basic Usage with Lists, Tuples, and Strings
my_list = ["a", "a", "b", "c"]
count_a = my_list.count("a")
print(count_a) # 2
my_tuple = ("a", "a", "b", "c")
count_b = my_tuple.count("a")
print(count_b) # 2
my_string = "Hello World"
count_c = my_string.count("l")
print(count_c) # 3
Output:
2
2
3
Those examples represent the basic usage of the count() function.
Using count() with Index Ranges
On objects like strings, bytes, and bytes arrays we can also provide optional arguments with indexes between which we would like to count elements.
my_string = "Hello World"
count_d = my_string.count("l", 2, 4)
print(count_d) # 2
my_bytes = b"Hello World"
count_e = my_bytes.count(b"l", 2, 3)
print(count_e) # 1
my_bytes_array = bytearray.fromhex("13 00 00 00 08 00")
count_f = my_bytes_array.count(b"\x00", 3, 6)
print(count_f) # 2
Output:
2
1
2
Please note that the second index position is already not included in the search range.
Key Points to Remember about the count() Function
-
Versatile: Works with multiple iterable data types (lists, tuples, strings, bytes, byte arrays, and ranges).
-
Optional Index Ranges: For strings, bytes, and byte arrays, you can specify a range with start and end.
-
Case Sensitivity: The
count()method is case-sensitive for strings. -
Efficiency: The
count()function is optimized for quick lookups in most iterable types.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!