Counting the occurrence of unique values in a list can be done by using the dictionary.

In Python, a dictionary is a list of key-value pairs that are not in order. Each key is unique.

  • The values in dictionaries can be changed, which is what it means to be “mutable.”
  • They are used to store values in a way that lets them be quickly and easily retrieved with a key. In Python, dictionaries are set up with curly braces {}  and are separated by colons :.

The keys of the dictionary would be the unique values, and the values would be their count. You can iterate through the list and increment the count for each value in the dictionary. This provides an efficient way to count the occurrences of unique values in a list.

Here is an example:

def count_occurrence(lst):
    count = {}
    for item in lst:
        if item in count:
            count[item] += 1
        else:
            count[item] = 1
    return count

# Example usage
list = [1, 2, 3, 1, 2, 3, 4, 5, 1, 2, 3]
print(count_occurrence(list))

Output:

{1: 3, 2: 3, 3: 3, 4: 1, 5: 1}

Categorized in:

Tagged in: