Python - Unique values count of each Key

PythonServer Side ProgrammingProgramming

When it is required to find unique values count of every key, an iteration along with the ‘append’ method is used.

Example

Below is a demonstration of the same

my_list = [12, 33, 33, 54, 84, 16, 16, 16, 58]

print("The list is :")
print(my_list)

filtered_list = []

elem_count = 0

for item in my_list:
if item not in filtered_list:
elem_count += 1
filtered_list.append(item)

print("The result is :")
print(elem_count)

Output

The list is :
[12, 33, 33, 54, 84, 16, 16, 16, 58]
The result is :
6

Explanation

• A list is defined and is displayed on the console.

• An empty list is defined,

• An integer is assigned to 0.

• The original list is iterated over.

• If an element present in the original list is not present in the second list, the integer is incremented by 1.

• The number is appended to the empty list.

• This is the output that is displayed on the console.

Published on 15-Sep-2021 12:09:10