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:

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:

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:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join