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
- The code prompts the user to enter a list of words and assigns it to the variable
word_list
. - We iterate over
word_list
usingfor
loop. Inside the loop, length of each word gets added tototal_length
variable. - Average length is calculated by dividing
total_length
by the number of words inword_list
.
Answered By
3 Likes
Related Questions
What will be the output produced by following code fragments?
x = "hello" + \ "to Python" + \ "world" for char in x : y = char print (y, ' : ', end = ' ')
What will be the output produced by following code fragments?
x = "hello world" print (x[:2], x[:-2], x[-2:]) print (x[6], x[2:4]) print (x[2:-3], x[-4:-2])
Predict the output of the following code snippet ?
a = [1, 2, 3, 4, 5] print(a[3:0:-1])
Predict the output of the following code snippet?
arr = [1, 2, 3, 4, 5, 6] for i in range(1, 6): arr[i - 1] = arr[i] for i in range(0, 6): print(arr[i], end = "")