Find Second Largest Element in Python

Find the second largest distinct element in a list.

BeginnerList ProgramsExample 12 of 25
find-second-largest-element.py
Run in browser
1# Program to find second largest distinct element in a list
2
3numbers = list(map(float, input("Enter numbers separated by space: ").split()))
4
5unique_numbers = sorted(set(numbers))
6
7if len(unique_numbers) < 2:
8 print("Need at least two distinct elements.")
9else:
10 print("Second largest element:", unique_numbers[-2])

Output

Enter numbers separated by space: 1 3 4 4 2
Second largest element: 3.0

What's going on

We convert to a set to remove duplicates, sort, and take the second last element.