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

Each Answer to this Q is separated by one/two green lines.

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)

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)

What should happen if there are more than 1 longest string (think ’12’, and ’01’)?

Try that to get the longest element

max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])

And then regular foreach

for st in mylist:
    if len(st)==max_length:...

len(each) == max(len(x) for x in myList) or just each == max(myList, key=len)

To get the smallest or largest item in a list, use the built-in min and max functions:

 lo = min(L)
 hi = max(L)  

As with sort, you can pass in a “key” argument that is used to map the list items before they are compared:

 lo = min(L, key=int)
 hi = max(L, key=int)

Looks like you could use the max function if you map it correctly for strings and use that as the comparison. I would recommend just finding the max once though of course, not for each element in the list.

def LongestEntry(lstName):
  totalEntries = len(lstName)
  currentEntry = 0
  longestLength = 0
  while currentEntry < totalEntries:
    thisEntry = len(str(lstName[currentEntry]))
    if int(thisEntry) > int(longestLength):
      longestLength = thisEntry
      longestEntry = currentEntry
    currentEntry += 1
  return longestLength

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.