π Day 60/150 – Find Second Largest Element in Python
The second largest element is the number that is just smaller than the largest number in the list.
Example:
[10, 20, 4, 45, 99] → Largest = 99, Second Largest = 45
Let’s explore different ways to find it π
πΉ Method 1 – Using Sorting
numbers = [10, 20, 4, 45, 99] numbers.sort() print("Second Largest:", numbers[-2])
πΉ Method 2 – Using set() + max()
numbers = [10, 20, 4, 45, 99]
numbers = list(set(numbers))
numbers.remove(max(numbers))
print("Second Largest:", max(numbers))
πΉ Method 3 – Using Loop
numbers = [10, 20, 4, 45, 99]
largest = second = float('-inf')
for num in numbers:
if num > largest:
second = largest
largest = num
elif num > second and num != largest:
second = num
print("Second Largest:", second)
πΉ Method 4 – Taking User Input
numbers = list(map(int, input("Enter numbers: ").split()))
numbers = sorted(set(numbers))
print("Second Largest:", numbers[-2])
π‘ Key Takeaways
- Sorting is the easiest way
- set() helps remove duplicates
- Loop method is efficient because it scans only once
- Always consider duplicate values when finding the second largest


0 Comments:
Post a Comment