310

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:
        do_something()
    elif ___________________: #else if each is the longest string contained in mylist:
        do_something_else()

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user104997
  • 3,135
  • 2
  • 18
  • 7

7 Answers7

749

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
Paolo Bergantino
  • 480,997
  • 81
  • 517
  • 436
  • 2
    Won't work for Python 2.4. See [this post](http://bytes.com/topic/python/answers/37337-key-argument-max#post140122) and [this post](http://bytes.com/topic/python/answers/37337-key-argument-max#post140143) for code to implement under 2.4. – Kumba Aug 24 '12 at 01:40
  • 23
    It only returns the first longest string: for example, `print(max(["this", "does", "work"], key=len))` only returns `"this"` instead of returning all of the longest strings. – Anderson Green Jan 22 '14 at 00:55
  • ditto @AndersonGreen. Can the method be redeployed in a way that captures two+ elements of the list meeting the call (key) equally well? – David Shaked Jan 27 '16 at 18:39
  • Following up on my question from earlier, I've linked a response that remedies the first-item-if-all-else-equal problem... – David Shaked Jan 27 '16 at 19:12
  • @DavidShaked Of course, it is possible to [sort a list of strings by length](http://stackoverflow.com/questions/2587402/sorting-python-list-based-on-the-length-of-the-string) to obtain a list of the longest strings. – Anderson Green Jan 27 '16 at 20:14
  • 7
    To get every largest element, in linear time, you have to do `m=max(map(len,xs)); [x for x in xs if len(x) == m]`. I don't think it can be done nicely in one line. – Thomas Ahle Mar 29 '16 at 18:57
  • @ThomasAhle: Not "nicely", but you can abuse nested listcomp to avoid recomputing the `max` for every comparison: `[x for m in (max(map(len, xs)),) for x in xs if len(x) == m]`. The "outer loop" loops over the one-tuple with the `max` computed exactly once, which both avoids recomputing it and (on Py3) ensures `m` is a local variable, which can speed up the code a bit. – ShadowRanger Mar 07 '18 at 03:21
  • Does not return correctly if the strings have spaces. – Wayne Workman Mar 27 '23 at 04:25
14
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)
pableiros
  • 14,932
  • 12
  • 99
  • 105
  • The `logestWord` definition here should be the accepted answer because it handles strings with spaces. The `max()` function does not handle this. – Wayne Workman Mar 27 '23 at 04:26
8

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:...
Elazar Leibovich
  • 32,750
  • 33
  • 122
  • 169
3

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

HarryM
  • 1,875
  • 13
  • 7
3

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)

http://effbot.org/zone/python-list.htm

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.

Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72
Gavin H
  • 10,274
  • 3
  • 35
  • 42
  • 1) doesn't work for string with spaces, 2) throws err using list of strings from my example: `ValueError: invalid literal for int() with base 10: 'dd'` – daddyodevil Jun 28 '23 at 07:47
0

This is a linear time implementation I came up with. If there exists multiple elements of the same size, then will return the first element with the largest size. :

s = ["a", "b", "c", "d", "aa", "bb", "cc", "dd", "ddd", "dd d"]
maxl = ""
for i in s:
    if len(i) > len(maxl):
        maxl = i
print(maxl)

If you want the index of the string with max length you can use the following:

s = ["a", "b", "c", "d", "aa", "bb", "cc", "dd", "ddd", "dd d"]
shuffle(s)   #from random import shuffle
print(s)
maxl_idx = 0
for i,j in enumerate(s):
    if len(j) > len(s[maxl_idx]):
        maxl_idx = i
print(maxl_idx, '\t', s[maxl_idx])
daddyodevil
  • 184
  • 2
  • 13
0
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