w3resource

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


Length of Strings in List

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]

Visual Presentation:

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

Sample Solution:

Python Code:

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

# Define a function named 'test' that takes a list of strings 'strs' as input
def test(strs):
    # Use the map function to apply the len function to each string in 'strs', and convert the result to a list
    return [*map(len, strs)]

# Create a list of strings 'strs' with specific elements
strs = ['cat', 'car', 'fear', 'center']

# Print the original list of strings
print("Original strings:")
print(strs)

# Print a message indicating the operation to be performed on the list
print("Lengths of the said list of non-empty strings:")

# Print the result of the test function applied to the 'strs' list
print(test(strs))

# Create a different list of strings 'strs' with specific elements
strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']

# Print the original list of strings
print("\nOriginal strings:")
print(strs)

# Print a message indicating the operation to be performed on the list
print("Lengths of the said list of non-empty strings:")

# Print the result of the test function applied to the modified 'strs' list
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.

For more Practice: Solve these Related Problems:

  • Write a Python program to calculate and return a list of lengths for each non-empty string in an input list.
  • Write a Python program to iterate over a list of strings and output the length of each string using a loop.
  • Write a Python program to use list comprehension to generate the lengths of strings from a given list.
  • Write a Python program to create a new list containing the character counts of each string from the input list.

Go to:


Previous: Find the strings in a list, starting with a given prefix.
Next: 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.

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.