w3resource

Python: Find the lengths of a list of non-empty strings

Python Programming Puzzles: Exercise-14 with Solution

Write a Python program to find the length of a given list of non-empty strings.

Input:
['cat', 'car', 'fear', 'center']
Output:
[3, 3, 4, 6]

Input:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Output:
[3, 3, 7, 5, 2, 4, 0]

Pictorial Presentation:

Python: Find the lengths of a list of non-empty strings.

Sample Solution:

Python Code:

#License: https://bit.ly/3oLErEI
def test(strs):
     return [*map(len, strs)]
strs =  ['cat', 'car', 'fear', 'center']
print("Original strings:")
print(strs)
print("Lengths of the said list of non-empty strings:")
print(test(strs))
strs =  ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
print("\nOriginal strings:")
print(strs)
print("Lengths of the said list of non-empty strings:")
print(test(strs))

Sample Output:

Original strings:
['cat', 'car', 'fear', 'center']
Lengths of the said list of non-empty strings:
[3, 3, 4, 6]

Original strings:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Lengths of the said list of non-empty strings:
[3, 3, 7, 5, 2, 4, 0]

Flowchart:

Flowchart: Python - Find the lengths of a list of non-empty strings.

Python Code Editor :

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

Previous: Find the strings in a list, starting with a given prefix.
Next: Find the longest string of a list of strings.

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.