w3resource

Python: Find the longest string of a list of strings

Python Programming Puzzles: Exercise-15 with Solution

Write a Python program to find the longest string in a given list of strings.

Input:
['cat', 'car', 'fear', 'center']
Output:
center

Input:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Output:
shatter

Pictorial Presentation:

Python: Find the longest string of a list of strings.

Sample Solution-1:

Python Code:

def test(words):
    return  max(words, key=len) 
strs =  ['cat', 'car', 'fear', 'center']
print("Original strings:")
print(strs)
print("Longest string of the said list of strings:")
print(test(strs))
strs =  ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
print("\nOriginal strings:")
print(strs)
print("Longest string of the said list of strings:")
print(test(strs))

Sample Output:

Original strings:
['cat', 'car', 'fear', 'center']
Longest string of the said list of strings:
center

Original strings:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Longest string of the said list of strings:
shatter

Flowchart:

Flowchart: Python - Find the longest string of a list of strings.

Sample Solution-2:

Python Code:

#License: https://bit.ly/3oLErEI

def test(words):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    alphabet = alphabet + alphabet.upper()
    alphabet_dict = {}
    for k in alphabet:
        alphabet_dict[k] = True
    alphabet_set = set(alphabet)
    max_word = words[0]
    for el in words:
        if not ((set(el) <= alphabet_set) and (set(el) == set(el).intersection(alphabet_dict.keys()))):
            continue
        if len(el) >= len(max_word):
            max_word = el
    return max_word
strs =  ['cat', 'car', 'fear', 'center']
print("Original strings:")
print(strs)
print("Longest string of the said list of strings:")
print(test(strs))
strs =  ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
print("\nOriginal strings:")
print(strs)
print("Longest string of the said list of strings:")
print(test(strs))

Sample Output:

Original strings:
['cat', 'car', 'fear', 'center']
Longest string of the said list of strings:
center

Original strings:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Longest string of the said list of strings:
shatter

Flowchart:

Flowchart: Python - Find the longest string of a list of strings.

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Find the lengths of a list of non-empty strings.
Next: Find the strings in a list containing a given substring.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.