Length of the longest wordWrite a Python program to read a list of words and return the length of the longest word present within the list elements
Question
Length of the longest word
Write a Python program to read a list of words and return the length of the longest word present within the list elements.
Solution
Sure, here is a simple Python program that reads a list of words and returns the length of the longest word present within the list elements:
def find_longest_word(word_list):
word_len = []
for n in word_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][0]
print(find_longest_word(["PHP", "Exercises", "Backend"]))
In this program:
- We define a function
find_longest_word
that takes a list of words as an argument. - Inside this function, we initialize an empty list
word_len
. - We then loop over each word in the input list, appending a tuple to
word_len
that contains the length of the word and the word itself. - We sort
word_len
. By default, sort() will sort the list in ascending order based on the first element of the tuple (i.e., the word length). - We return the length of the longest word, which is the first element of the last tuple in
word_len
(since it's sorted in ascending order, the last element will be the longest word). - Finally, we call the function with a list of words and print the result.
Similar Questions
How do you get the length of a list in Python?Answer( Please choose a correct answer ) CLEARlen(my_list)my_list.size()my_list.count()length(my_list)
Which built-in function is used to find the length of a sequence (such as a string or list) in Python? count() length() len() size()
Longest Substring Without Repeating CharactersGiven a string s find the length of the longest substring without repeating characters.
Write a program to count number of words in a given string whose length is greater than 3.For example:Input Resultpython is easier than C3
Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.