What is an efficient way to find the most common element in a Python list?
My list items may not be hashable so can't use a dictionary. Also in case of draws the item with the lowest index should be returned. Example:
>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
A simpler one-liner:
Building on Luiz's answer, but satisfying the "in case of draws the item with the lowest index should be returned" condition:
Example:
Borrowing from here, this can be used with Python 2.7:
Works around 4-6 times faster than Alex's solutions, and is 50 times faster than the one-liner proposed by newacct.
To retrieve the element that occurs first in the list in case of ties: