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.
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!!!!!!
🌍 Related Tutorial: How to Find the Shortest String in a Python List?
Python Max Length of String in List
To find the maximum length of a string in a given list, you can use the max(lst, 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(lst, key=len))
Here’s a more detailed example:
def get_max_length(lst): return len(max(lst, 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([])) # Value Error!!!
How to Find the Index of the Longest String in a List (Python)?
To find the index of the longest string in a Python list, use the built-in enumerate(list)
function to make a list of indexed tuples from your list (e.g., ['a', 'b']
–> [(0, 'a'), (1, 'b')]
).
Pass the enumerated list into the max()
function using a custom key function key=lambda x: len(x[1])
to compare the length of the second tuple elements, i.e., the strings.
The result is an indexed tuple (index, string)
such as (0, 'Alice')
that contains the index of the longest string in the list ['Alice', 'Bob', 'Pete']
.
Here’s the code example:
def get_max_str_index(lst): return max(enumerate(lst), key=lambda x: len(x[1])) print(get_max_str_index(['Alice', 'Bob', 'Pete'])) # (0, 'Alice') print(get_max_str_index(['aaa', 'aaaa', 'aa'])) # (1, 'aaaa') print(get_max_str_index([''])) # (0, '') print(get_max_str_index([])) # ValueError: max() arg is an empty sequence
If you only need the index of the longest string, use max(enumerate(lst), key=lambda x: len(x[1]))[0]
to access the index of the longest string in the enumerated string list of (index, string)
tuples.
Like so:
def get_max_str_index(lst): return max(enumerate(lst), key=lambda x: len(x[1]))[0] print(get_max_str_index(['Alice', 'Bob', 'Pete'])) # 0 print(get_max_str_index(['aaa', 'aaaa', 'aa'])) # 1 print(get_max_str_index([''])) # 0 print(get_max_str_index([])) # ValueError: max() arg is an empty sequence
Let’s smooth this technical tutorial out with a bit of programming humor…
Programming Humor
💡 Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.
~~~
- Question: Why do Java programmers wear glasses?
- Answer: Because they cannot C# …!
Feel free to check out our blog article with more coding jokes. 😉
Also, you may find this tutorial interesting because it doesn’t just try to find the longest string in a list of strings, but arbitrary regex patterns or partial matches.
If you want to find the longest string in a set, this tutorial is the right one for you.