[Tutor] Finding the shortest word in a list of words

Kent Johnson kent37 at tds.net
Tue Jan 20 12:45:58 CET 2009


On Mon, Jan 19, 2009 at 9:47 PM, Emad Nawfal (عماد نوفل)
<emadnawfal at gmail.com> wrote:

> Thanks John for this. Although the decorate-sort-undecorate idiom looks so
> natural to me now, I don't think I would have found it on my own. I have
> that deja vu effect towards it.

decorate-sort-undecorate is pretty much obsolete since the key=
parameter was added to sort() in Python 2.4. Since Python 2.5 you can
also use key= with min() and max() so your problem can be solved very
simply and tersely:

In [1]: words = "man woman children he".split()

In [2]: min(words, key=len)
Out[2]: 'he'

Kent


More information about the Tutor mailing list