How to Count the Same Numbers in a Python List?

Estimated read time 1 min read

To count the occurrences of the same numbers in a Python list, you can use the collections module, specifically the Counter class. Here’s an example:

from collections import Counter

my_list = [1, 2, 3, 2, 4, 3, 5, 4, 6, 5, 1, 1, 1, 1]

# Create a Counter object from the list
num_counter = Counter(my_list)

# Print the occurrences of each number
for num, count in num_counter.items():
    print(f"Number {num} occurs {count} times in the list.")

In this example, we have a list my_list containing some numbers. We then create a Counter object num_counter from the list using Counter(my_list). The Counter class is a built-in class in Python that provides an easy way to count the occurrences of elements in a collection, such as a list.

We then use a for loop to iterate over the items in the num_counter object, which gives us the distinct numbers in the list as keys, and their corresponding counts as values. We use the items() method of Counter to get a list of key-value pairs, where the keys represent the numbers and the values represent their counts. Finally, we print the occurrences of each number using a formatted string with the num and count variables.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply