Knowee
Questions
Features
Study Tools

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 wordWrite a Python program to read a list of words and return the length of the longest word present within the list elements

🧐 Not the exact question you are looking for?Go ask a question

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:

  1. We define a function find_longest_word that takes a list of words as an argument.
  2. Inside this function, we initialize an empty list word_len.
  3. 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.
  4. 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).
  5. 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).
  6. Finally, we call the function with a list of words and print the result.

This problem has been solved

Similar Questions

Have the function LongestWord(sen) take the sen parameter being passed and return the longest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty. Words may also contain numbers, for example "Hello world123 567"

class Solution: def longestCommonPrefix(self, v: List[str]) -> str: ans="" v=sorted(v) first=v[0] last=v[-1] for i in range(min(len(first),len(last))): if(first[i]!=last[i]): return ans ans+=first[i] return ans

Find the length of a list without using the len() function.

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)

Write a Python program to split a string to words

1/3

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.