I'm having a list as shown here. a=[1936,2401,2916,4761,9216,9216,9604,9801]
I want to get the value which have more duplicates. In here it is '9216' how can i get this value? Thanks
Asked
Active
Viewed 1.2k times
6
![](../../users/profiles/2208850.webp)
Totem
- 6,563
- 4
- 32
- 60
![](../../users/profiles/4542278.webp)
Dimuth Ruwantha
- 591
- 2
- 8
- 25
4 Answers
13
You can use collections.Counter
for this:
from collections import Counter
a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801]
c = Counter(a)
print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
[(9216, 2)] # a set containing the element, and it's count in 'a'
From the docs:
![](../../users/profiles/2208850.webp)
Totem
- 6,563
- 4
- 32
- 60
2
There's two standard library ways to do this:
from statistics import mode
most_common = mode([3, 2, 2, 2, 1]) # 2
most_common = mode([3, 2]) # StatisticsError: no unique mode
collections.Counter.most_common
:
from collections import Counter
most_common, count = Counter([3, 2, 2, 2, 1]).most_common(1)[0] # 2, 3
most_common, count = Counter([3, 2]).most_common(1)[0] # 3, 1
Both are identical in terms of performance, but the first raises an exception when there is no unique most common element and the second returns the frequency as well.
![](../../users/profiles/2132312.webp)
Matthew D. Scholefield
- 2,033
- 2
- 23
- 38
1
Here is another one not using counter
a=[1936,2401,2916,4761,9216,9216,9604,9801]
frequency = {}
for element in a:
frequency[element] = frequency.get(element, 0) + 1
# create a list of keys and sort the list
# all words are lower case already
keyList = frequency.keys()
keyList.sort()
print "Frequency of each word in the word list (sorted):"
for keyElement in keyList:
print "%-10s %d" % (keyElement, frequency[keyElement])
![](../../users/profiles/1751920.webp)
Stefan Gruenwald
- 2,342
- 22
- 24
0
https://docs.python.org/2.7/library/collections.html#counter
from collections import Counter Counter(a).most_common(1)
![](../../users/profiles/5356629.webp)
gyu-don
- 586
- 3
- 14