0
0
PythonProgramBeginner · 2 min read

Python Program to Find Second Largest in List

You can find the second largest number in a list in Python by using sorted(set(your_list))[-2] or by iterating through the list to track the largest and second largest values.
📋

Examples

Input[1, 2, 3, 4, 5]
Output4
Input[10, 20, 20, 8, 6]
Output10
Input[5, 5, 5]
OutputNo second largest element found
🧠

How to Think About It

To find the second largest number, first remove duplicates to avoid counting the same number twice. Then sort the unique numbers or scan through the list to find the largest and second largest values. The second largest is the number just smaller than the largest.
📐

Algorithm

1
Remove duplicate numbers from the list.
2
Sort the unique numbers in ascending order.
3
Pick the second last number from the sorted list as the second largest.
4
If there is no second largest (list too short), return a message.
💻

Code

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

Dry Run

Let's trace the list [10, 20, 20, 8, 6] through the code

1

Remove duplicates

Original list: [10, 20, 20, 8, 6] Unique list: [10, 20, 8, 6]

2

Check length

Length of unique list is 4, which is >= 2, so continue

3

Sort unique list

Sorted unique list: [6, 8, 10, 20]

4

Return second largest

Second largest is the second last element: 10

StepUnique ListSorted ListSecond Largest
After removing duplicates[10, 20, 8, 6]
After sorting[6, 8, 10, 20]
Result10
💡

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

Iterative approach
python
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]))
This method finds the second largest in one pass without sorting, which is faster for large lists.
Using heapq module
python
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]))
Using <code>heapq.nlargest</code> efficiently finds the top two largest numbers without full sorting.

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.

ApproachTimeSpaceBest For
Sorting unique elementsO(n log n)O(n)Simple and clear code
Iterative scanO(n)O(1)Large lists, better performance
Heapq.nlargestO(n log k)O(n)Finding top k elements efficiently
💡
Always remove duplicates first to correctly find the second largest number.
⚠️
Not handling cases where the list has fewer than two unique numbers causes errors or wrong results.