-2

I need to write a code where a function takes in a list and then returns the longest string from that list.

So far I have:

def longestword(alist):     
    a = 0     
    answer = '' 
    for i in alist:         
        x = i     
    if x > a:         
        a = x         
        answer = x     
    elif i == a:         
        if i not in alist:             
            answer = answer + ' ' + i     
    return answer

The example I have is longestword([11.22,"hello",20000,"Thanksgiving!",True]) which is supposed to return 'Thanksgiving!' but my function always returns True.

chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
ANON
  • 75
  • 1
  • 9
  • Please us a descriptive title. Otherwise you have predjudiced most users against your question before they even open it! – Paul Rooney Dec 02 '16 at 03:09
  • My apologies for asking it the wrong way the first time everybody! I'm brand new to this site! – ANON Dec 02 '16 at 03:29
  • The thing with this list is that it's not homogeneous; if you're defining length in terms of value then 20000 would be the "longest"; if you're trying to do it based on character count then each element would have to be a string. – Makoto Dec 02 '16 at 03:31
  • I see what your saying, the question asks that i return the longest string. not in terms of numbers. – ANON Dec 02 '16 at 03:33
  • 1
    So, are you ignoring numbers in your list outright or turning them into strings? – Makoto Dec 02 '16 at 03:34
  • i would assume turning them in to strings. All i know is that the question i have in front of me says that with the list i gave in the question that Thanksgiving! should be returned from it. So if i can get some help at least doing that then it would be great – ANON Dec 02 '16 at 03:36
  • If you're turning it all to strings, that's not too tough - but at this point it becomes a duplicate [of this question](http://stackoverflow.com/q/873327/1079354), so I'd encourage you to check it out. – Makoto Dec 02 '16 at 03:37
  • i don't believe that i'm turning them to strings. I just need to return whatever value in the list has the most index positions. Like "11.22" has 5 and "hello" has 5 and "Thanksgiving!" has 13. I just need to return the value that has the most index positions. – ANON Dec 02 '16 at 03:41
  • Those are not called "index positions", they're called characters. Except that 11.22 does not have five characters, because it's not a string -- it doesn't have *any* characters. If you want, you can get the string representation of that number -- "11.22", which does have five characters; that's what people are referring to when they say "turning the items into strings". – Larry Lustig Dec 02 '16 at 04:17
  • Possible duplicate of [Python's most efficient way to choose longest string in list?](http://stackoverflow.com/questions/873327/pythons-most-efficient-way-to-choose-longest-string-in-list) – OneCricketeer Mar 21 '17 at 21:55

4 Answers4

3

For starters, this always assigns x to the very last value in the list, which in your example is True.

for i in alist:         
    x = i  

And you should try not to access a loop value outside of the loop because, again, it's the last value of the thing you looped over, so True

elif i == a:

The key to solving the problem is to pick out which values are strings (using isinstance()) and tracking the longest length ones (using the len() function)

def longeststring(lst):
  longest = ""
  for x in lst:
    if isinstance(x, str) and len(x) > len(longest):
      longest = x
  return longest

Do be mindful of equal length strings. I don't know the requirements of your assignment.

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
1

I prefer to keep the for loops to a minimum; here's how I find the longest string in a list:

listo = ["long     word 1  ",       " super OMG long    worrdddddddddddddddddddddd", "shortword" ]

lenList = []
for x in listo:
    lenList.append(len(x))
length = max(lenList)

print("Longest string is: {} at {} characters.".format(listo[lenList.index(length)] , length))
grego
  • 189
  • 1
  • 1
  • 8
0

Why not use...

str_list = [x for x in alist if isinstance(x, str)]

longestword = sorted(str_list, key=len, reverse=True)[0]

Using a list comprehension, create new_list by iterating the elements of your original list and retaining only the strings with.

And then your list will be sorted by the sorted() function.

Applying the key=len argument, your list will be sorted by the length of the list element using the built-in-function len().

And with the reverse=True argument, your list will be returned sorted in descending order, i.e. longest first.

Then you select index [0] of the sorted list which in this case, is the longest string.

To complete then:

def longestword(alist):

    str_list = [x for x in alist if isinstance(x, str)]

    longestword = sorted(str_list, key=len, reverse=True)[0]

    return longestword

As Gavin rightly points out below, the sorting could be achieved without having to pass the reverse=True argument by returning the last element in the list with [-1], i.e.:

longestword = sorted(str_list, key=len)[-1]
bonz
  • 21
  • 3
  • Looks good! However, from the problem as specified doesn't seem you can guarantee that all elements of the list are strings. Maybe filter the list for strings first, a slight simplification could be to edit the sorted call using `sorted(tokens, key=len)[-1]` too. – Gavin Apr 09 '20 at 13:48
  • Hi and welcome to SO! Unfortunately it was asked to find only the strings, not other kind of data (see the accepted answer that handles it) – manuel_b Apr 09 '20 at 14:32
  • 1
    Thanks for the feedback @Gavin! I will also add your modification. – bonz Apr 10 '20 at 04:31
0

You can try something like this :

def longest_string(some_list):
    only_str = [s for s in some_list if isinstance(s, str)]
    return max(only_str, key=len)

This method will create a list of strings named only_str. Then it will return the max length string using max() function.

When we run the longest_string() method with the example provided in the question:

some_list = [11.22,"hello",20000,"Thanksgiving!",True]
longest_string(some_list)

The output is: 'Thanksgiving!'

Hope this solves this problem!!