Largest, Smallest, Second Largest, Second Smallest in a List - Python
Last Updated :
11 Dec, 2025
Given a list of numbers, the task is to find four values: largest, smallest, second largest and second smallest element.
For example:
For the list [4, 1, 7, 3, 9]:
Largest: 9
Smallest: 1
Second Largest: 7
Second Smallest: 3
Let's explore different methods to find all of these in Python.
Single Loop
This method goes through the list once while updating four variables that keep track of the largest, smallest, second largest, and second smallest as each element is processed.
Python
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
l1 = l2 = float('-inf')
s1 = s2 = float('inf')
for x in a:
if x > l1:
l2, l1 = l1, x
elif x > l2:
l2 = x
if x < s1:
s2, s1 = s1, x
elif x < s2:
s2 = x
print(l1, s1, l2, s2)
Explanation:
- x > l1 updates the largest, and shifts the previous largest to l2.
- x > l2 updates the second largest.
- x < s1 updates the smallest, and shifts the previous smallest to s2.
- x < s2 updates the second smallest.
Using heap
This method uses heapq.nsmallest() and heapq.nlargest() to directly extract the two smallest and two largest values from the list.
Python
import heapq
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
s1, s2 = heapq.nsmallest(2, a)
l1, l2 = heapq.nlargest(2, a)
print(l1, s1, l2, s2)
Explanation:
- nsmallest(2, a) returns the smallest and second smallest.
- nlargest(2, a) returns the largest and second largest.
Using min() and max()
This method first retrieves the smallest and largest values using built-ins using min() and max(), removes them from the list, and obtains the next two values from the remaining elements.
Python
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
l1 = max(a)
s1 = min(a)
a.remove(l1)
a.remove(s1)
l2 = max(a)
s2 = min(a)
print(l1, s1, l2, s2)
Explanation:
- max(a) and min(a) extract extreme values.
- After removing them from a, calling max(a) and min(a) again gives the second extremes.
Using sorting
This method sorts the entire list using sort() and then reads the required values using fixed positions.
Python
a = [12, 45, 2, 41, 31, 10, 8, 6, 4]
a.sort()
print(a[-1], a[0], a[-2], a[1])
Explanation: After sorting, a[0] and a[1] store the smallest values, while a[-1] and a[-2] store the largest values in order.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice