0
0
PythonProgramBeginner · 2 min read

Python Program to Find Second Largest Element in List

You can find the second largest element in a list by first removing duplicates with set(), then sorting it and accessing the second last element with sorted(set(lst))[-2].
📋

Examples

Input[1, 2, 3, 4, 5]
Output4
Input[10, 20, 20, 30, 40]
Output30
Input[5, 5, 5, 5]
OutputNo second largest element
🧠

How to Think About It

To find the second largest element, first remove any repeated numbers so you only have unique values. Then, sort these unique numbers from smallest to largest. The second largest will be the one just before the biggest number in this sorted list. If there is only one unique number, then there is no second largest element.
📐

Algorithm

1
Get the input list of numbers.
2
Convert the list to a set to remove duplicates.
3
Check if the set has at least two elements; if not, return a message that no second largest exists.
4
Sort the unique elements in ascending order.
5
Return the element at the second last position in the sorted list.
💻

Code

python
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]))
Output
30
🔍

Dry Run

Let's trace the list [10, 20, 20, 30, 40] through the code

1

Convert list to set

Input list: [10, 20, 20, 30, 40] -> Unique set: {40, 10, 20, 30}

2

Check length of unique set

Length is 4, which is >= 2, so continue

3

Sort unique elements

Sorted list: [10, 20, 30, 40]

4

Return second largest

Second largest element is sorted_list[-2] = 30

StepUnique SetSorted ListSecond 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

Using two variables to track largest and second largest
python
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]))
This method does not require sorting and works in one pass, which is faster for large lists but a bit more complex to understand.
Using max() and removing the max element
python
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]))
This method uses built-in max() twice and removes the largest element first; it's simple and efficient for moderate list sizes.

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.

ApproachTimeSpaceBest For
Sorting unique elementsO(n log n)O(n)Simplicity and small to medium lists
Two variables trackingO(n)O(1)Large lists needing speed and low memory
Remove max then max againO(n)O(n)Simple code with moderate efficiency
💡
Always remove duplicates before finding the second largest to avoid errors with repeated max values.
⚠️
Beginners often forget to handle cases where the list has less than two unique elements, causing errors.