Skip to content

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:

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*


PySaaS: The Pure Python SaaS Starter Kit

馃殌 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 馃檹