Tip: How to find the longest String in a List in Python

Patrick Loeber

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 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 *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses