Code Explanation:
Import the Counter Class
from collections import Counter
Counter is imported from the collections module.
It is used to count the frequency of each element in a list or iterable.
Create a List of Numbers
nums = [1, 2, 2, 3, 3, 3]
A list named nums is created.
The list contains repeating numbers: 1, 2, 2, 3, 3, 3.
Count the Frequency of Elements
counted = Counter(nums)
Counter(nums) counts how many times each number appears.
The result will be: {1:1, 2:2, 3:3}
1 appears 1 time
2 appears 2 times
3 appears 3 times
Get the Most Common Element
most_common = counted.most_common(1)
most_common(1) returns a list with the top 1 most frequent element.
Output structure: [(element, frequency)]
So it becomes: [(3, 3)] → meaning number 3 appears 3 times.
Print Only the Element (Not the Count)
print(most_common[0][0])
most_common[0] → (3, 3)
most_common[0][0] → 3 (the element, not the count)
Final printed output:
3
Final Output
3


0 Comments:
Post a Comment