Python Program to return the Length of the Longest Word from the List of Words



When it is required to return the length of the longest word from a list of words, a method is defined that takes a list as parameter. It checks if an element is in the list and depending on this, the output is displayed.

Example

Below is a demonstration of the same

def find_longest_length(my_list):
   max_length = len(my_list[0])
   temp = my_list[0]

   for element in my_list:
      if(len(element) > max_length):

         max_length = len(element)
         temp = element
   return max_length

my_list = ["ab", "abc", "abcd", "abcde"]
print("The list is :")
print(my_list)
print("The result is :")
print(find_longest_length(my_list))

Output

The list is :
['ab', 'abc', 'abcd', 'abcde']
The result is :
5

Explanation

  • A method named ‘find_longest_length’ is defined that takes a list as parameter.

  • The length of the list is assigned to a variable.

  • The list is iterated over, and every element’s length is checked to see if it is greater than length of the first element of the list.

  • If so, this is assigned as the maximum length.

  • It is returned as output.

  • Outside the method, a list is defined and is displayed on the console.

  • The method is called by passing the required parameters.

  • The output is displayed on the console.


Advertisements