Python | Longest String in list
Sometimes, while working with Python Lists, we can have a problem in which we receive Strings as elements and wish to compute the String which has maximum length. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using loop
This is the brute method in which we perform this task. In this, we run a loop to keep a memory of longest string length and return the string which has max length in list.
# Python3 code to demonstrate working of
# Longest String in list
# using loop
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print["The original list : " + str[test_list]]
# Longest String in list
# using loop
max_len = -1
for ele in test_list:
if len[ele] > max_len:
max_len = len[ele]
res = ele
# printing result
print["Maximum length string is : " + res]
|
Method #2 : Using max[] + key
This method can also be used to solve this problem. In this, we use inbuilt max[] with “len” as key argument to extract the string with the maximum length.
# Python3 code to demonstrate working of
# Longest String in list
# using max[] + key
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print["The original list : " + str[test_list]]
# Longest String in list
# using max[] + key
res = max[test_list, key = len]
# printing result
print["Maximum length string is : " + res]
|
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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