0

I have a list of strings like the one below:

stringList = ["a" , "aa", "aaa", "aaaa", "aaab", "aaac"]

What I am trying to do is return all the longest strings in the list, I have tried using the max function but it only returns one value, whereas in this case there are 3 strings with a length of 4.

Thanks for any help!

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
h1h1
  • 730
  • 4
  • 11
  • 19
  • 1.find the length of longest string 2.filter the length equals that – iMom0 May 02 '13 at 17:10
  • What do you mean exactly? Maybe this? >> http://stackoverflow.com/questions/873327/pythons-most-efficient-way-to-choose-longest-string-in-list < – grooveplex May 02 '13 at 17:11

3 Answers3

8

Use list comprehension and max:

>>> lis= ["a" , "aa", "aaa", "aaaa", "aaab", "aaac"]

>>> le = max(len(x) for x in lis)   #find out the max length      

>>> [x for x in lis if len(x) == le]  #now filter list based on that max length
['aaaa', 'aaab', 'aaac']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

Something like this maybe:

longest_len = 0
longest_strings = []

for s in stringList:
    if len(s) > longest_len:
        longest_len = len(s)
        longest_strings = [s]
    elif len(s) == longest_len:
        longest_strings.append(s)
viraptor
  • 33,322
  • 10
  • 107
  • 191
  • 1
    This is definitively the fastest algorithm, not the most pythonic though.. – Alexander Kuzmin May 02 '13 at 17:12
  • 1
    It is not fastest. Too many wasted `append`s. – Oleh Prypin May 02 '13 at 17:14
  • @BlaXpirit timeit and be surprised... double list traversal is 1.18 times slower at 100 elements and 1.22 times slower at 10000 elements. Strings generated by `sizes = [abs(int(random.gauss(20, 10)))+1 for _ in range(length)] ; stringList = [''.join(random.sample(longstring, s)) for s in sizes]` – viraptor May 02 '13 at 17:35
  • If the list is already sorted by length, it's 1.25 times faster... but if you know the list is sorted you can just read the results from the end. – viraptor May 02 '13 at 17:40
0

A single list comprehension (even though the list is processed many times):

[s for s in stringList if len(s) == len(max(stringList, key=len))]

Since Python v2.5, min() and max() have an optional argument key that allows you to specify the comparison method.

Quant Metropolis
  • 2,602
  • 2
  • 17
  • 16
  • 1
    The list is processed more than twice: the `if` is checked for every `s in stringList`, so `len(max(stringList, key=len))` is computed `len(stringList)` times. It will show quadratic performance, more's the pity. – DSM May 02 '13 at 18:08
  • @DSM: you're right. I still have to get used to the interpreted nature of Python. – Quant Metropolis May 02 '13 at 18:23