Subtle difference when apply `set()` to find max count items in a list

Viewed 37

A friend has asked this question, and I just cannot find a good explanation for it. (He knows how the max() and key works in this case)

Given a list of scores as this:

lst = ['A', 'B', 'B', 'B', 'C', 'C', 'C', 'E']

>>> max(lst, key=lst.count)
'B'
>>> max(set(lst), key=lst.count)
'C'
# if run min - will return different results - w/ and w/o set():
>>> min(lst, key=lst.count)
'A'
>>> min(set(lst), key=lst.count)
'E'
>>> 
1 Answers

max and min return the first maximal / minimal element in an iterable.

lst.count("A") and lst.count("E") are equal (evaluating to 1), and so are lst.count("B") and lst.count("C") (evaluating to 3). A set is unordered in Python, and converting a list to a set does not preserve its order. (The internal order of a set is not exactly random, but arbirtrary.)

This is the reason why the results differ.

If you want to keep the order, but have unique elements, you could do:

unique_lst = sorted(set(lst), key=lst.index)
Related