Programming Problems · Q3
Q.Write a program to find the largest and the second largest elements in a given list of elements.
Odisha ChseTextbookSubjective· 3mImportance★★★★★est
73% · 22/30 Questions
✓ Free question
Sort a copy of the list in descending order; the largest is at index 0 and the second largest is the first later element that differs from it (so duplicates of the maximum
don't get counted twice). A one-pass loop version is also shown.
The idea
"Second largest" usually means the second largest distinct value — in [9, 9, 5] it is 5,
not 9. Sorting makes this easy: after sorting in descending order, walk forward until the value changes.
Program (sort-based — simplest)
# Largest and second largest element of a list
n = int(input("How many elements? "))
lst = []
for i in range(n):
lst.append(int(input("Enter element " + str(i + 1) + ": ")))
s = sorted(lst, reverse=True) # descending copy; original list untouched
largest = s[0]
second = None
for value in s[1:]:
if value != largest: # first value different from the maximum
second = value
break
print("Largest :", largest)
if second is None:
print("Second largest : does not exist (all elements are equal)")
else:
print("Second largest :", second)
Sample run
How many elements? 6
Enter element 1: 12
Enter element 2: 45
Enter element 3: 7
Enter element 4: 45
Enter element 5: 30
Enter element 6: 2
Largest : 45
Second largest : 30
One-pass alternative (no sorting)
largest = second = None
for x in lst:
if largest is None or x > largest:
second, largest = largest, x
elif x != largest and (second is None or x > second):
second = x
Key lines explained:
sorted(lst, reverse=True)returns a new descending list (unlikelst.sort(), it doesn't change the original).- The
if value != largestguard is what handles duplicates — with[45, 45, 30, ...]it skips the second45and correctly reports30. - The one-pass version updates two trackers as it scans: a new maximum demotes the old one to
second.
✓Final answer
Sort descending, take s[0] as the largest and the first value != s[0] as the second largest —
for [12, 45, 7, 45, 30, 2]: largest 45, second largest 30 (duplicates of the maximum are skipped).
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.