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 browser1# Program to find second largest distinct element in a list23numbers = list(map(float, input("Enter numbers separated by space: ").split()))45unique_numbers = sorted(set(numbers))67if 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.