How to Find the Longest String in a Python List?

Use Python’s built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.

How to Find the Longest String in a Python List?

Problem Formulation

Given a Python list of strings. Find the string with the maximum number of characters—the longest string in the list.

Here are a few example list of strings and the desired output:

# ['Alice', 'Bob', 'Pete']   ---->   'Alice'
# ['aaa', 'aaaa', 'aa']      ---->   'aaaa'
# ['']                       ---->   ''
# []                         ---->   ''

Solution: max() function with key function argument len()

Use Python’s built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.

Here’s the code definition of the get_max_str() function that takes a list of strings as input and returns the longest string in the list or a ValueError if the list is empty.

def get_max_str(lst):
    return max(lst, key=len)

Here’s the output on our desired examples:

print(get_max_str(['Alice', 'Bob', 'Pete']))
# 'Alice'

print(get_max_str(['aaa', 'aaaa', 'aa']))
# 'aaaa'

print(get_max_str(['']))
# ''

print(get_max_str([]))
# ValueError

Border Case: What if the List is Empty?

If you want to return an alternative value in case the list is empty, you can modify the get_max_str() function to include a second optional argument:

def get_max_str(lst, fallback=''):
    return max(lst, key=len) if lst else fallback


print(get_max_str([]))
# ''

print(get_max_str([], fallback='NOOOOOOOOO!!!!!!'))
# NOOOOOOOOO!!!!!!

Solution with For Loop

A less Pythonic but, for beginner coders, more readable version is the following loop-based:

def get_max_str(lst, fallback=''):
    if not lst:
        return fallback

    max_str = lst[0]   # list is not empty

    for x in lst:
        if len(x) > len(max_str):
            max_str = x

    return max_str


print(get_max_str(['Alice', 'Bob', 'Pete']))
# 'Alice'

print(get_max_str(['aaa', 'aaaa', 'aa']))
# 'aaaa'

print(get_max_str(['']))
# ''

print(get_max_str([], fallback='NOOOOOOOOO!!!!!!'))
# NOOOOOOOOO!!!!!!