12
votes

I was making a function that returns the longest string value from a list. My code works when there is only one string with the most characters. I tried to make it print all of the longest strings if there were more than one, and I do not want them to be repeated. When I run this, it only returns 'hello', while I want it to return 'ohman' and 'yoloo' also. I feel like the problem is in the line if item not list:, but I have tried everything and it doesn't work.

list = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
def length(lists):
    a = 0 
    answer = ''
    for item in lists:
        x = len(item) 
    if x > a:
        a = x
        answer = item
    elif x == a:
        if item not in list:
            answer = answer + ' ' + item
    return answer
print length(list)
5

5 Answers

23
votes

First, we can find the maximum length of any string in the list:

stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
#maxlength = max([len(s) for s in stringlist])
maxlength = max(len(s) for s in stringlist)  # omitting the brackets causes max 
                                             # to operate on an iterable, instead
                                             # of first constructing a full list
                                             # in memory, which is more efficient

A little explanation. This is called a list comprehension, which allows you to comprehend one list as another list. The code [len(s) for s in stringlist] means "generate a list-like object, by taking stringlist, and for every s in that list, give me instead, len(s) (the length of that string).

So now we have a list [2, 5, 3, 5, 5, 5]. Then we call the built-in max() function on that, which will return 5.

Now that you have the max length, you can filter the original list:

longest_strings = [s for s in stringlist if len(s) == maxlength]

This does just as it reads in english: "For each string s in stringlist, give me that string s, if len(s) is equal to maxlength."

Finally, if you want to make the result unique, you can use the set() constuctor to generate a unique set:

unique_longest_strings = list(set(longest_strings))

(We are calling list() to turn it back into a list after removing the duplicates.)


This boils down to:

ml = max(len(s) for s in stringlist)
result = list(set(s for s in stringlist if len(s) == ml))

Note: Don't use a variable named list, as it overrides the meaning of the name for the list type.

11
votes

I highly endorse Jonathon Reinhart's answer, but I just couldn't hold it... How about this?

max(map(len, stringlist))

There is no need to write a list comprehension, this is even simpler...

0
votes

Maybe you have miswrote the line if item not in list:,and the indent is wrong,modified as below:

def length(lists):
    a = 0
    answer = ""


    for item in lists:
        x = len(item)
        if x > a:
            a = x
            answer = item
        elif x == a:
            if item not in ans:
                answer = answer + " " + item
    return answer

But I think Jonathon Reinhart have provided a better method.

0
votes

I had same problem. I figured out my solution in this way:

myList =['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
def get_longest_strings(myList):
        longest=len(max(myList,key=len))
        for each in myList:
                if(longest==len(each)):
                       #common_result is list to store longest string in list
                       common_result.append(each)
        return common_result
print(common_result)
0
votes

Something like this...

def allLongestStrings(inputArray):
    maxLength = len(max(inputArray, key = len))
    
    newArray = []
    
    lengthArray = len(inputArray)
    
    for i in range(lengthArray):
        if(len(inputArray[i])==maxLength):
            newArray.append(inputArray[i])
    return newArray