# Find all of the values in a list that are repeated the most

I have a list of objects and I would like to see which ones are the most common. It is easy to find the or a most common object using python's Counter, but I haven't found a simple way to find all of the most common objects. The code below is working but I would guess there's a better way to do this.

from collections import Counter

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

counts = Counter(input_lst)
ranked_counts = counts.most_common().copy()
first_common_obj = ranked_counts.pop(0)
equally_common_objs = [first_common_obj]
while ranked_counts:
next_obj = ranked_counts.pop(0)
if first_common_obj == next_obj:
equally_common_objs.append(next_obj)
else:
break

print(equally_common_objs)


It would be easier, and have better performance, to iterate over Counter.most_common() rather than using .pop(0) lots.

From here you just want to use next until the value is not the same. Which is effectively what you're doing with .pop.

from collections import Counter

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

counts = Counter(input_lst)
items = iter(counts.most_common())
value, amount = next(items)
values = [value]
while True:
value, a = next(items)
if amount != a:
break
values.append(value)

print(values)


This is effectively grouping consecutive values together, and so you can instead use itertools.groupby rather than roll your own.

from collections import Counter
from itertools import groupby

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

_, values = next(groupby(Counter(input_lst).most_common(), lambda i: i))
values = [value for value, _ in values]
print(values)

• The first solution hit a StopIteration and then crashed, but the second solution worked for me (Python 3.7.6). May 6, 2020 at 19:54
• @jss367 That issue is present in your original code. May 6, 2020 at 19:54
• @jss367 There is an additional issue that will cause a StopIteration error in both my solutions and an IndexError in yours. Please properly test your code, before blaming me for causing errors in your code. May 6, 2020 at 20:21