When it is required to read a list of words and return the length of the longest list, a method can be defined that iterates through the list and gets the length of every string in the list of strings using the ‘len’ method.
Below is a demonstration of the same −
Example
def longest_length_string(my_string): len_str = len(my_string[0]) temp_val = my_string[0] for i in my_string: if(len(i) > len_str): len_str = len(i) temp_val = i print("The word with the longest length is:", temp_val, " and length is ", len_str) my_string = ["three", "Jane", "quick", "lesson", 'London', 'newyork'] print("The list is :") print(my_string) print("The method to find the longest string in the list is called") longest_length_string(my_string)
Output
The list is : ['three', 'Jane', 'quick', 'lesson', 'London', 'newyork'] The method to find the longest string in the list is called The word with the longest length is: newyork and length is 7
Explanation
A method named ‘longest_length_string’ is defined.
It takes a list of strings as a parameter.
The list is iterated over, and the length of every string in the list is determined.
The largest of these values is determined and returned as output.
A list of strings is defined and is displayed on the console.
The method is called bypassing this list as a parameter.
The output is displayed on the console.