-5

How can I print the most common element of a list without importing a library?

l=[1,2,3,4,4,4]

So I want the output to be 4.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • I'm brand-new here,i've not get used to this type of asking.I'm sorry.Could you please answer my question? – vasilistheod Jan 12 '17 at 11:50
  • 2
    No. Because **this isn't a code-writing service**. Learn [ask], and actually put in some effort yourself before dumping it on SO. – jonrsharpe Jan 12 '17 at 11:57
  • 2
    Possible duplicate of [Python most common element in a list](http://stackoverflow.com/questions/1518522/python-most-common-element-in-a-list) – CaptainObvious Jan 12 '17 at 11:59

2 Answers2

1

You can get the unique values first:

l = [1, 2, 3, 4, 4, 4]
s = set(l)

then you can create list of (occurrences, value) tuples

freq = [(l.count(i), i) for i in s]  # [(1, 1), (1, 2), (1, 3), (3, 4)]

get the "biggest" element (biggest number of occurrences, the biggest value if there are more than one with the same number of occurrences):

result = max(freq)  # (3, 4)

and print the value:

print(result[1])  # 4

or as a "one-liner" way:

l = [1, 2, 3, 4, 4, 4]
print(max((l.count(i), i) for i in set(l))[1])  # 4
Doncho Gunchev
  • 2,159
  • 15
  • 21
0
lst=[1,2,2,2,3,3,4,4,5,6]
from collections import Counter
Counter(lst).most_common(1)[0]

Counter(lst) returns a dict of element-occurence pairs. most_common(n) returns the n most common elements from the dict, along with the number of occurences.

Anomitra
  • 1,111
  • 15
  • 31