Python Program to Find Second Largest in List
sorted(set(your_list))[-2] or by iterating through the list to track the largest and second largest values.Examples
How to Think About It
Algorithm
Code
def find_second_largest(numbers): unique_numbers = list(set(numbers)) if len(unique_numbers) < 2: return "No second largest element found" unique_numbers.sort() return unique_numbers[-2] # Example usage nums = [10, 20, 20, 8, 6] print(find_second_largest(nums))
Dry Run
Let's trace the list [10, 20, 20, 8, 6] through the code
Remove duplicates
Original list: [10, 20, 20, 8, 6] Unique list: [10, 20, 8, 6]
Check length
Length of unique list is 4, which is >= 2, so continue
Sort unique list
Sorted unique list: [6, 8, 10, 20]
Return second largest
Second largest is the second last element: 10
| Step | Unique List | Sorted List | Second Largest |
|---|---|---|---|
| After removing duplicates | [10, 20, 8, 6] | ||
| After sorting | [6, 8, 10, 20] | ||
| Result | 10 |
Why This Works
Step 1: Remove duplicates
Using set() removes repeated numbers so the second largest is meaningful.
Step 2: Sort the list
Sorting arranges numbers from smallest to largest, making it easy to pick the second largest.
Step 3: Pick second largest
The second largest number is the element just before the last in the sorted list, accessed by [-2].
Alternative Approaches
def find_second_largest_iter(numbers): first = second = float('-inf') for num in numbers: if num > first: second = first first = num elif first > num > second: second = num if second == float('-inf'): return "No second largest element found" return second print(find_second_largest_iter([10, 20, 20, 8, 6]))
import heapq def find_second_largest_heap(numbers): unique_numbers = list(set(numbers)) if len(unique_numbers) < 2: return "No second largest element found" largest_two = heapq.nlargest(2, unique_numbers) return largest_two[1] print(find_second_largest_heap([10, 20, 20, 8, 6]))
Complexity: O(n log n) time, O(n) space
Time Complexity
Sorting the unique elements takes O(n log n) time, where n is the number of unique elements.
Space Complexity
Creating a set and list of unique elements uses O(n) extra space.
Which Approach is Fastest?
The iterative approach is O(n) time and O(1) space, making it faster and more memory efficient than sorting.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sorting unique elements | O(n log n) | O(n) | Simple and clear code |
| Iterative scan | O(n) | O(1) | Large lists, better performance |
| Heapq.nlargest | O(n log k) | O(n) | Finding top k elements efficiently |