Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 iterates through each word to find the maximum length and returns it.
Example
Below is a demonstration of the same ?
def find_longest_length(word_list):
max_length = len(word_list[0])
temp = word_list[0]
for element in word_list:
if len(element) > max_length:
max_length = len(element)
temp = element
return max_length
word_list = ["ab", "abc", "abcd", "abcde"]
print("The list is :")
print(word_list)
print("The result is :")
print(find_longest_length(word_list))
Output
The list is : ['ab', 'abc', 'abcd', 'abcde'] The result is : 5
Using Built-in Functions
Python provides a more concise approach using the max() function with the key parameter ?
def find_longest_length_builtin(word_list):
return len(max(word_list, key=len))
word_list = ["Python", "Programming", "Code", "Development"]
print("The list is :")
print(word_list)
print("The longest word length is :")
print(find_longest_length_builtin(word_list))
The list is : ['Python', 'Programming', 'Code', 'Development'] The longest word length is : 11
Comparison
| Method | Time Complexity | Code Length | Readability |
|---|---|---|---|
| Manual Loop | O(n) | Longer | More explicit |
| Built-in max() | O(n) | Shorter | More concise |
Explanation
A method named 'find_longest_length' is defined that takes a list as parameter.
The length of the first element is assigned to a variable as initial maximum.
The list is iterated over, and every element's length is checked to see if it is greater than the current maximum length.
If so, this is assigned as the new maximum length.
The maximum length is returned as output.
The built-in approach uses
max()withkey=lento find the longest word, then returns its length.
Conclusion
Use the manual loop approach for learning purposes and when you need more control. Use the built-in max() function for cleaner, more Pythonic code in production.
