Python Program to Find Second Largest Element in List
set(), then sorting it and accessing the second last element with sorted(set(lst))[-2].Examples
How to Think About It
Algorithm
Code
def second_largest(lst): unique = set(lst) if len(unique) < 2: return "No second largest element" sorted_list = sorted(unique) return sorted_list[-2] # Example usage print(second_largest([10, 20, 20, 30, 40]))
Dry Run
Let's trace the list [10, 20, 20, 30, 40] through the code
Convert list to set
Input list: [10, 20, 20, 30, 40] -> Unique set: {40, 10, 20, 30}
Check length of unique set
Length is 4, which is >= 2, so continue
Sort unique elements
Sorted list: [10, 20, 30, 40]
Return second largest
Second largest element is sorted_list[-2] = 30
| Step | Unique Set | Sorted List | Second Largest |
|---|---|---|---|
| 1 | {40, 10, 20, 30} | ||
| 2 | {40, 10, 20, 30} | ||
| 3 | {40, 10, 20, 30} | [10, 20, 30, 40] | |
| 4 | {40, 10, 20, 30} | [10, 20, 30, 40] | 30 |
Why This Works
Step 1: Remove duplicates
Using set() removes repeated numbers so we only compare unique values.
Step 2: Check for enough elements
If there is less than two unique numbers, there can't be a second largest, so we return a message.
Step 3: Sort the unique numbers
Sorting arranges numbers from smallest to largest, making it easy to pick the second largest.
Step 4: Pick the second largest
The second largest is the element just before the last in the sorted list, accessed by sorted_list[-2].
Alternative Approaches
def second_largest(lst): if len(lst) < 2: return "No second largest element" first = second = float('-inf') for num in lst: if num > first: second = first first = num elif first > num > second: second = num if second == float('-inf'): return "No second largest element" return second print(second_largest([10, 20, 20, 30, 40]))
def second_largest(lst): unique = set(lst) if len(unique) < 2: return "No second largest element" unique.remove(max(unique)) return max(unique) print(second_largest([10, 20, 20, 30, 40]))
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 a sorted list uses O(n) extra space for unique elements.
Which Approach is Fastest?
The two-variable tracking method 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) | Simplicity and small to medium lists |
| Two variables tracking | O(n) | O(1) | Large lists needing speed and low memory |
| Remove max then max again | O(n) | O(n) | Simple code with moderate efficiency |