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
1# 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.
After this program
If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.