Write a program to iterate a given list and count the occurrence of each element and create a dictionary to show the count of each element.
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
sample_list = [11, 45, 8, 11, 23, 45, 23, 45, 89]
print("Original list ", sample_list)
count_dict = dict()
for item in sample_list:
if item in count_dict:
count_dict[item] += 1
else:
count_dict[item] = 1
print("Printing count of each item ", count_dict)
Original list [11, 45, 8, 11, 23, 45, 23, 45, 89]
Printing count of each item {11: 2, 45: 3, 8: 1, 23: 2, 89: 1}
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.
Sign in to save your progress and continue exactly where you left off.