Largest, Smallest, Second Largest, Second Smallest in a List-Python
Last Updated :
03 Mar, 2025
We are given a list of numbers and our task is to find the largest, smallest, second largest and second smallest elements in the list. For example, if the list is [4, 1, 7, 3, 9], the largest is 9, the smallest is 1, the second largest is 7 and the second smallest is 3. Let's explore different ways to solve this problem efficiently in Python.
Using min() and max()
This approach utilizes Python’s built-in max() and min() functions to find the largest and smallest elements. By removing them from the list, we can efficiently determine the second largest and second smallest values. This method is effective as it avoids unnecessary sorting.
Python
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
# find largest and smallest values
l1 = max(a)
s1 = min(a)
# remove them from the list
a.remove(l1)
a.remove(s1)
# find second largest and second smallest
l2 = max(a)
s2 = min(a)
print(f"Largest: {l1}, Smallest: {s1}, Second Largest: {l2}, Second Smallest: {s2}")
OutputLargest: 45, Smallest: 2, Second Largest: 41, Second Smallest: 4
Explanation: This code first finds the largest and smallest elements using max() and min(), then removes them to avoid interference. It then applies max() and min() again to determine the second largest and second smallest elements from the remaining numbers.
Using heap
heapq module provides a structured way to find the smallest and largest elements efficiently. Using nsmallest(2, a) and nlargest(2, a), we can extract the required values in a well-optimized manner. This method is particularly useful when working with large datasets where structured extraction is preferred over manual iteration.
Python
import heapq
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
# get two smallest and two largest elements
s1, s2 = heapq.nsmallest(2, a)
l1, l2 = heapq.nlargest(2, a)
print(f"Largest: {l1}, Smallest: {s1}, Second Largest: {l2}, Second Smallest: {s2}")
OutputLargest: 45, Smallest: 2, Second Largest: 41, Second Smallest: 4
Explanation: heapq.nsmallest(2, a) retrieves the two smallest values, while heapq.nlargest(2, a) extracts the two largest values.
Using for loop
A single pass through the list can determine all four values efficiently by maintaining only four variables. This method eliminates the need for extra function calls or sorting, making it one of the fastest and most memory-efficient solutions. It ensures minimal computation while keeping the logic straightforward.
Python
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
l1 = l2 = float('-inf') # largest and second largest
s1 = s2 = float('inf') # smallest and second smallest
for n in a:
# update largest and second largest
if n > l1:
l2, l1 = l1, n
elif n > l2:
l2 = n
# update smallest and second smallest
if n < s1:
s2, s1 = s1, n
elif n < s2:
s2 = n
print(f"Largest: {l1}, Smallest: {s1}, Second Largest: {l2}, Second Smallest: {s2}")
OutputLargest: 45, Smallest: 2, Second Largest: 41, Second Smallest: 4
Explanation: loop updates l1, l2 for larger values and s1, s2 for smaller ones, ensuring l1 and s1 store the largest and smallest, while l2 and s2 hold the second largest and second smallest.
Using sorting
Sorting the list and directly selecting the required elements is the most intuitive approach but not the most efficient. While simple to implement, sorting the entire list takes unnecessary extra steps when only four values are needed. This method is best suited for small datasets where performance is not a concern.
Python
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
a.sort()
print(f"Largest: {a[-1]}, Smallest: {a[0]}, Second Largest: {a[-2]}, Second Smallest: {a[1]}")
OutputLargest: 45, Smallest: 2, Second Largest: 41, Second Smallest: 4
Explanation: This code sorts a in ascending order, allowing direct access to the largest (a[-1]), second largest (a[-2]), smallest (a[0]) and second smallest (a[1]) elements.
Similar Reads
Get Second Largest Number in Python List Using Bubble Sort Finding the second-largest number in a list is a common programming task that involves sorting the list in ascending order. Bubble sort is a simple sorting algorithm that can be used for this purpose. In this article, we will explore the logic behind finding the second largest number using bubble so
3 min read
Python program to Sort a list according to the second element of sublist Sorting a list by the second element of each sublist means rearranging the sublists based on the value at index 1. For example, given the list [[1, 3], [2, 1], [4, 2], [3, 5]], sorting by the second element results in [[2, 1], [4, 2], [1, 3], [3, 5]], where the second elements (1, 2, 3, 5) are in as
3 min read
How to get the n-largest values of an array using NumPy? Let's see the program for how to get the n-largest values of an array using NumPy library. For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy.argsort() function of NumPy then applying slicing concept with negative indexing. Syntax: numpy.argsort(arr, ax
2 min read
Sort a List According to the Length of the Elements - Python We are given a list of strings and our task is to sort the list based on the length of each string. For example, if the input is ["Python", "C", "Java", "JavaScript", "Go"], the output should be ["C", "Go", "Java", "Python", "JavaScript"] since shorter strings come first.Using sorted() sorted() func
3 min read
Python - Sort list of list by specified index When working with a list of lists, we often need to sort the inner lists based on the values at a specific index. Sorting by a specified index is useful in the custom ordering of multidimensional data. In this article, we will explore different ways to sort a list of lists by a specified index in Py
3 min read