Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the shortest string in a list in Python

Tags:

python

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).

like image 804
leecbaker Avatar asked Aug 29 '11 10:08

leecbaker


People also ask

How do I find the smallest string in a list 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.

How do you find the length of a string in a list Python?

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.


1 Answers

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" 
like image 130
Jeremy Avatar answered Sep 25 '22 06:09

Jeremy