Open In App

Longest String in list – Python

Last Updated : 29 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a list of strings, and our task is to find the longest string present in the list. If there are multiple strings with the maximum length, we should return the first one that appears. For example, given a = [“alpha”, “gamma”, “epsilon”, “delta”], the longest string is “epsilon”. Let’s discuss different methods to do this in Python.

Using max() with key=len

max() function efficiently finds the longest string by comparing elements based on their length.

[GFGTABS]
Python

a = ["alpha", "gamma", "epsilon", "delta"]  

l = max(a, key=len)  
print(l)


[/GFGTABS]

Output

epsilon

Explanation:

  • max(a, key=len) finds the string with the maximum length.
  • This method runs in O(n) time, making it the most efficient approach.

Using for loop

A simple for loop can manually track the longest string while iterating through the list.

[GFGTABS]
Python

a = ["alpha", "gamma", "epsilon", "delta"]  

l = ""  
for i in a:  
    if len(i) > len(l):  
        l = i  

print(l) 


[/GFGTABS]

Output

epsilon

Explanation:

  • initialize l with an empty string and then keep on updating it when a longer string is found.
  • It runs in O(n) time but is less concise than max().

Using sorted() and Indexing

Sorting the list based on string length and selecting the last element provides another way to find the longest string.

[GFGTABS]
Python

a = ["alpha", "gamma", "epsilon", "delta"]  

l = sorted(a, key=len)[-1]  
print(l)


[/GFGTABS]

Output

epsilon

Explanation:

  • sorted(a, key=len) sorts strings by length in ascending order of their lengths.
  • element [-1] returns te last element of the list which will be of longest length after sorting.
  • Sorting takes O(n log n) time, making this approach less efficient.

Using functools.reduce()

reduce() function compares strings and returns the longest one.

[GFGTABS]
Python

from functools import reduce  

a = ["alpha", "gamma", "epsilon", "delta"]  

l = reduce(lambda x, y: x if len(x) > len(y) else y, a)  
print(l)


[/GFGTABS]

Output

epsilon

Explanation: reduce() accumulates the longest string by comparing lengths.

Using heapq.nlargest() for Multiple Longest Strings

If we need to find all strings with the longest length, we can use heapq.nlargest().

[GFGTABS]
Python

import heapq  

a = ["alpha", "gamma", "epsilon", "delta", "omicron"]  

l = max(map(len, a))  
ls = [word for word in a if len(word) == l]  

print(ls)


[/GFGTABS]

Output

['epsilon', 'omicron']

Explanation:

  • max(map(len, a)) finds the longest length.
  • list comprehension extracts all strings of that length.
  • this method is useful when multiple strings have the same maximum length.

Related articles:



Next Article
Practice Tags :

Similar Reads