Find the longest and smallest string in a list – Single line using python

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.

Traditional approach

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.

finding the longest word in a list

The output of the above code is,

Strong

one-liner

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,

max(list, key=len)

The max method is given two arguments.

  1. The list itself
  2. 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.

one-liner to find the longest string in a list

The output of this code is also

Strong

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.

one-liner to find the smallest string in a list

The output of this code is,

bye

Conclusion

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.

Happy coding!