This seems like a pretty simple problem, but I'm looking for a short and sweet way of doing it that is still understandable (this isn't code golf).
Given a list of strings, what's the easiest way to find the shortest string?
The way that is most obvious to me is roughly:
l = [...some strings...] lens = map(l, len) minlen, minind = min(lens) shortest = l[minind]
but that seems like a lot of code for this problem (at least in python).
To find the smallest of given List of strings based on length in Python, call min() builtin function, pass the strings to compare as arguments to min() function, and also pass len() function for key parameter. min() function returns the string with the smallest length based on the key.
To get the length of a list in Python, you can use the built-in len() function. Apart from the len() function, you can also use a for loop and the length_hint() function to get the length of a list.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With