Python’s most efficient way to choose longest string in list?

I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1

For example:

mylist = ['abc','abcdef','abcd']

for each in mylist:
    if condition1:
    elif ___________________: #else if each is the longest string contained in mylist:

Surely there’s a simple list comprehension that’s short and elegant that I’m overlooking?


From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)

Leave a Reply

Your email address will not be published. Required fields are marked *