Signup/Sign In
PUBLISHED ON: FEBRUARY 15, 2021

How to Choose the Longest String in a Python List?

In this article, we will learn to find the longest string from a List in Python. We will use some built-in functions and some custom code as well. Let's first have a quick look over what is s list in Python.

Python List

Python has a built-in data type called list. It is like a collection of arrays with different methodology. Data inside the list can be of any type say, integer, string or a float value, or even a list type. The list uses comma-separated values within square brackets to store data. Lists can be defined using any variable name and then assigning different values to the list in a square bracket. The list is ordered, changeable, and allows duplicate values.

List Example

list1 = ["Ram", "Arun", "Kiran"]
list2 = [16, 78, 32, 67]
list3 = ["apple", "mango", 16, "cherry", 3.4]

Let us discuss two methods to find the longest string from a given Python List. The first method is a simple Brute Force Algorithm that uses for loop and another method uses built-in max() function of Python List that returns a string of maximum length.

Example: Find Longest String from List using For Loop

This is a Brute Force Approach. It simply uses for loop to iterate over the elements of the given list. It checks the length of each string element and returns the string of maximum length.

#input list
list1 = ['apple', 'banana', 'watermelon', 'orange'] 

max_len = -1
for ele in list1: 
    if(len(ele) > max_len): 
        max_len = len(ele) 
        res = ele 
        
print("Longest String is : ", res) 


Longest String is : watermelon

Example: Find Longest String from List using max() Function

This approach involves built-in max() function to find maximum or longest string from the given Python List. max() function takes two arguments, the iterable and other argument is key. Key = len to extract the string with the maximum length.

#input list
list1 = ['apple', 'banana', 'watermelon', 'orange'] 
res = max(list1, key=len) 
print("Longest String is  : ", res)


Longest String is : watermelon

Conclusion

In this article, we learned to find the longest string from the given Python List by using two methods. Firstly, we used for loop method and another was the max() function. We used some custom code as well.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.