How to find the shortest string in a list in Python
Takes linear time:
reduce(lambda x, y: x if len(x) < len(y) else y, l)
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"