Max Length String in a List in Python
The max
function in Python supports an optional “key” parameter which can be used to either access a property of the elements of a List or permute the elements in the List in a particular way.
The following example is a one-liner to get the maximum-length element from a Python List.
>>> x = ['1', '11', '111', '0000']
>>> max(x, key=len)
'0000'
The min
function also supports a key parameter in the same way as max
.
This also extends to any nested collection (since the string class supports __len__ just as a List or Dict does), so we can do other cool things like:
Return the shortest sublist in a nested list:
>>> x = [[0], [0,0], [0,0,0]]
>>> max(x, key=len)
[0]
Return an empty dictionary if it exists in a list:
>>> x = [{}, {1: 1}, {1: 1}]
>>> min(x, key=len)
Bonus: sets of sets (actually nested frozensets inside frozensets, since you can’t nest a set inside of a set since a set can’t be hashed).
>>> x = frozenset([frozenset([1]), frozenset([2, 3])])
>>> min(x, key=len)
frozenset([1])
>>> max(x, key=len)
frozenset([2, 3])