Python is known for giving developers the ability to do a lot of things in a single line of code.
This can get quite messy from time to time and can make the code unreadable, but there can be some exceptions. Today’s trick is going to be one.
Let us say that we want to find the most frequent element in a list.
One way to do that would be to save the frequency of elements in a dictionary and then get the key of the dictionary that has the highest value:
from collections import Counter
my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']
elements_count = {}
for element in my_list:
elements_count[element] = elements_count.get(element, 0) + 1
max_value = max(elements_count, key=elements_count.get)
print(max_value) # a
The second way to do that is a one line of Python in which we are doing the following:
- Convert the list into a set to remove duplicates
- Use the
max()
to find the maximum value based on the frequency of elements in a list usingkey=my_list.count
as a method argument:
my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']
print(max(set(my_list), key=my_list.count)) # a
That’s quite fast and dirty.
I hope you find it useful.