An approach
Find the most common items (Counter.most_common). Then find the item among those candidates who have a minimum index (list in the index dictionary, min {index: key} .iteritems ()).
The code
Stealing liberally from @gnibbler and @Jeff:
from collections import Counter def most_frequent_first(events): frequencies = Counter(events) indexes = {event: i for i, event in enumerate(events)} most_frequent_with_indexes = {indexes[key]: key for key, _ in frequencies.most_common()} return min(most_frequent_with_indexes.iteritems())[1] events = [123,123,456,456,456,123, 1, 2, 3, 2, 3] print(most_frequent_first(events))
Result
>>> print(most_frequent_first(events)) 456
The code
The best part of the code will provide you with frequency and index, showing that the code is working correctly. Here is an implementation that uses named_tuple:
from collections import Counter, namedtuple frequent_first = namedtuple("frequent_first", ["frequent", "first"]) def most_frequent_first(events): frequencies = Counter(events) indexes = {event: i for i, event in enumerate(events)} combined = {key: frequent_first(value, indexes[key]) for key, value in frequencies.iteritems()} return min(combined.iteritems(), key=lambda t: (-t[1].frequent, t[1].first)) events = [123,123,456,456,456,123, 1, 2, 3, 2, 3] print(most_frequent_first(events))
Result
>>> print(most_frequent_first(events)) (456, frequent_first(frequent=3, first=4))