Reputation: 11
Code:
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
Result:
4
In the above code, how does it work overall?
My understanding is, after the list test
is converted to a set, all duplicate elements are lost. Then how does the max
function find the value with the most occurances in the list?
Upvotes: 1
Views: 284
Reputation: 781721
Calling set(test)
doesn't change what's in the test
variable. It still contains the list with all the duplicates. This just filters out the duplicates in the first argument to max()
(to minimize the number of times it calls test.count()
), but the key
function is able to count them in the original list.
The problem you describe would occur if you reassigned test
, as in:
test = set(test)
print(max(test, key=test.count))
Upvotes: 1