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


Question

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 = ['123','123456','1234']

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

I'm brand new to python and I'm sure I'm just having a brain fart. Surely there's a simple list comprehension that's short and elegant that I'm overlooking?

Thanks!

1
208
4/3/2015 8:20:40 PM

Accepted Answer

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
539
5/16/2009 9:19:46 PM

def longestWord(some_list): 
    count = 0    #You set the count to 0
    for i in some_list: # Go through the whole list
        if len(i) > count: #Checking for the longest word(string)
            count = len(i)
            word = i
    return ("the longest string is " + word)

or much easier:

max(some_list , key = len)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon