fifiman fifiman - 5 months ago 19
Python Question

Longest strings from list

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)


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.