Tip - Find the longest String in a List in Python using the max() function
Learn how to easily find the longest String in a List in Python using the max() function.
The most efficient way to find the longest String in a List in Python is by using the max function with key=len:
#more
my_list = ["I", "like", "Python"]
word = max(my_list, key=len)
print(word) # Python
This is much simpler and more efficient than
my_list = ["I", "like", "Python"]
word = None
max_length = 0
for s in my_list:
if len(s) > max_length:
max_length = len(s)
word = s
print(word)
word = max(my_list, key=len)
print(word) # Python
max function with key argument¶
max(iterable, *[, key, default])max(arg1, arg2, *args[, key])
max returns the largest item in an iterable or the largest of two or more arguments.
The key argument specifies a one-argument ordering function like that used for list.sort().
The default argument specifies an object to return if the provided iterable is empty. If the iterable is empty and default is not provided, a ValueError is raised.
my_list = []
word = max(my_list, key=len)
# ValueError: max() arg is an empty sequence
With default argument:
my_list = []
word = max(my_list, key=len, default="")
# ""
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*