faqts : Computers : Programming : Languages : Python : Common Problems : Lists

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

8 of 10 people (80%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Is there an elegant way to select the longest string from a list?

Feb 20th, 2004 21:51
Washington Corrêa, W.J. van der Laan, Michael Chermside, Ellen Spertus,


Well, here's the best I can do:
Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> def longestString(aList):
...     """Returns the longest string in a sequence of strings.
...     In case of equal-length strings, returns the earliest."""
...     if not aList:
...             raise Exception, 'No items in list'
...     else:
...             longest = ''
...             for s in aList:
...                     if len(s) > len(longest):
...                             longest = s
...             return longest
...
Answer 2:
Maybe not shorter, but some people might regard it as more 'elegant'
>>> def longest(x,y):
...     """The longest string"""
...     if len(x)<len(y):
...             return y
...     else:
...             return x
...
>>> reduce(longest, ["a","bb","c","ee","xxxx","u"])
------------------------------
A shorter one:
l = ["a","bb","c","ee","xxxx","u"]
filter(lambda x: len(x)==max([len(x) for x in l]), l)
ok?