﻿ Python: Find the longest string of a list of strings - 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: 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
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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿