In this article, we shall see how to find the longest and smallest string in a list using python. This can be achieved in a single line. The traditional approach uses a ‘for loop‘ whereas this article teaches you how to find this without any loops.
Let us look at the traditional approach first. The traditional approach will use a for loop to iterate the strings one by one and then use the max() function to find the length of each string.
The output of the above code is,
The one-liner approach for this problem uses the max() method along with key arguments which takes the len method as its value.
The syntax is,
The max method is given two arguments.
- The list itself
- The len method as the key
This will apply the len() method to each element in the iterable and then returns the element or string with the maximum number of characters.
The output of this code is also
But, look how simple and elegant this solution. This greatly reduces the time complexity.
Now let us apply the same method to find the smallest string in the list.
The output of this code is,
As I have said before, there can be a lot of solutions to a problem. But, what matters the most is the way we approach the problem and solve it. Always use a pythonic approach to solve any problem.