How to Count the Number of Occurrences in an Array Using Python?

Estimated read time 2 min read

In Python, you can count the number of occurrences of a specific value in an array (or list) by using the built-in count() method. Here’s an example:

# Define the input array
input_array = [1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3]

# Define the value to count
value_to_count = 2

# Call the count() method on the input array
value_count = input_array.count(value_to_count)

# Print the result
print("The value {} appears {} times in the array.".format(value_to_count, value_count))


The value 2 appears 3 times in the array.

In this example, the count() method is called on the input_array and takes the value_to_count as an argument. It returns the number of occurrences of the value in the array, which is stored in the value_count variable. Finally, the result is printed using a formatted string to display the value and its count. Note that the count() method only counts the exact matches of the value in the array, and does not perform any type conversion or partial matching. If you need to perform more complex counting, such as counting the occurrences of a substring in a list of strings, you may need to use loops or other methods depending on the specific requirements of your task.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply