How to find the shortest string in a list in Python
The min
function has an optional parameter key
that lets you specify a function to determine the "sorting value" of each item. We just need to set this to the len
function to get the shortest value:
strings = ["some", "example", "words", "that", "i", "am", "fond", "of"]
print min(strings, key=len) # prints "i"
Takes linear time:
reduce(lambda x, y: x if len(x) < len(y) else y, l)
I'd use sorted(l, key=len)[0]