KnowledgeBoat Logo

Computer Science

Write a short Python code segment that adds up the lengths of all the words in a list and then prints the average (mean) length.

Python List Manipulation

2 Likes

Answer

word_list = eval(input("Enter a list of words: "))
total_length = 0
for word in word_list:
    total_length += len(word)
average_length = total_length / len(word_list)
print("Average length of words:", average_length)
Output
Enter a list of words: ["apple", "banana", "orange", "kiwi"] 
Average length of words: 5.25
Explanation
  1. The code prompts the user to enter a list of words and assigns it to the variable word_list.
  2. We iterate over word_list using for loop. Inside the loop, length of each word gets added to total_length variable.
  3. Average length is calculated by dividing total_length by the number of words in word_list.

Answered By

1 Like


Related Questions