There are many articles and videos that show you how to find the largest in a list. However, there are not that many articles that show you how to find the second largest element in a list or the second smallest element in a list.
Yes, I also agree that it can be less frequent when you need to find the second largest one, or the second smallest element. The less demand for it in our daily work, the less supply with tutorials on how to do it.
Now, as rare as it can be, I had a specific scenario recently in a Python script where I had to identify the second largest element in a list read from a CSV file. This got me inspired to write this article as I know someone else may also need it.
Now, without too much fluff, let’s get back to see how to do it.
As we are already used to expect for many tasks, there are definitely Python’s built-in functions that can help us, but I am not aware of any function that can help us get this one done entirely without some little tweaks from our side.
Before we move on, let us first think of how we would implement this without from an intuitive perspective:
- Sort the list and save the ordered list somewhere
- Remove the largest element
- Get the remaining largest element
Let us see this in action:
There is also another way where we don’t need to remove any element at all, but use the power of indexing.
So after we do the sorting, we are going to get the following:
As we can see, the largest element is at the end of the list. Now, to get the second largest element we need to get the second element starting from the right.
To do that, we can use negative indexing:
- To get the first element starting from the right, we need to use the index of -1.
- To get the second element starting from the right, we need to use the index of -2.
So yeah, we only need to use the index -2 on the sorted list to get that element:
That’s basically it. I hope you found this helpful.