Skip to content Skip to sidebar Skip to footer

Find The Two Longest Strings From A List || Or The Second Longest List In PYTHON

I'd like to know how i can find the two longest strings from a list(array) of strings or how to find the second longest string from a list. thanks

Solution 1:

You can do this using the standard heapq module:

>>> lst = ['hello', 'blah', 'boo', 'braininess']
>>> heapq.nlargest(2, lst, key=len)
['braininess', 'hello']

Solution 2:

Easiest way to do this is use the sorted() function by using another built-in function len as the key argument as follows;

>>> foo = ['dddd', 'ccc', 'bb', 'a', 'eeeee']
>>> sorted(foo, key=len)[-2]
'dddd'

or if you need the two longest:

>>> sorted(foo, key=len)[-2:]
['dddd', 'eeeee']

Solution 3:

If a is your list of strings, then a.sort(key=len) will sort your list of strings by their length. The longest would be a[-1], and the second longest would be a[-2]. `


Solution 4:

l = ['123', '12345', '12']
l.sort(key=lambda item: len(item))
l.[-1] # longest
l.[-2] # second longest

Post a Comment for "Find The Two Longest Strings From A List || Or The Second Longest List In PYTHON"