How to Find the Longest String in a Python Set?

Use Python’s built-in max() function with the key argument to find the longest string in a set. Call max(my_set, key=len) to return the longest string in the set using the built-in len() function to determine the weight of each string—the longest string has maximum length.

👉 Recommended Tutorial: How to Find the Longest String in a Python List?

Problem Formulation

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

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

# {'Alice', 'Bob', 'Pete'}   ---->   'Alice'
# {'aaa', 'aaaa', 'aa'}      ---->   'aaaa'
# {''}                       ---->   ''
# {}                         ---->   ''

Method 1: max() Function with Key Argument Set to len()

Use Python’s built-in max() function with a key argument to find the longest string in a set like so: max(s, key=len). This returns the longest string in the set s using the built-in len() function to determine 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 set of strings as input and returns the longest string in the list or a ValueError if the set is empty.

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

Here’s the output we obtain when running our desired examples:

print(get_max_str({'Alice', 'Bob', 'Pete'}))
# 'Alice'

print(get_max_str({'aaa', 'aaaa', 'aa'}))
# 'aaaa'

print(get_max_str({''}))
# ''

If you pass an empty set, Python will raise a ValueError: max() arg is an empty sequence because you cannot pass an empty iterable into the max() function.

print(get_max_str({}))
# ValueError: max() arg is an empty sequence

Method 2: Handling Empty Sets

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

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


print(get_max_str({}))
# ''

print(get_max_str({}, fallback='EMPTY!!!!!!'))
# EMPTY!!!!!!

Method 3: Not-So-Pythonic with For Loop

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

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

    max_str = ''   # set is not empty

    for x in my_set:
        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='EMPTY!!!!!!'))
# EMPTY!!!!!!

Method 4: Python Max Length of String in Set

To find the maximum length of a string in a given set, use the max(my_set, key=len) function to obtain the string with the maximum length and then pass this max string into the len() function to obtain the number of characters of the max string.

len(max(my_set, key=len))

Here’s a more detailed example:

def get_max_length(my_set):
    return len(max(my_set, key=len))


print(get_max_length({'Alice', 'Bob', 'Pete'}))
# 5

print(get_max_length({'aaa', 'aaaa', 'aa'}))
# 4

print(get_max_length({''}))
# 0

print(get_max_length({}))
# ValueError: max() arg is an empty sequence

Thanks for taking the time to read this article! 🙂 Feel free to join us – it’s fun and we have cheat sheets!

Programming Humor

👉 Recommended Tutorial: How to Get the Shortest String in a Python Set?