python program to find the second largest number in a list
In the python programming guide, we are going to learn:
-
write a python program to find the second largest element in the list
python program to find the second largest number in a list
The python program to find 2nd largest number in a list is as follows:
# Owner : TutorialsInhand Author : Devjeet Roy
numbers = list(map(int, input("Enter numbers: ").strip().split()))
max_num = 0
second_max = 0
if len(numbers) < 2:
print("List size must be 2 atleast!")
else:
for i in numbers:
if i > max_num:
second_max = max_num
max_num = i
elif i > second_max and i < max_num:
second_max = i
print("The second largest number is: ", second_max)
The output of the python program to find the second largest number in a list is as follows:
Enter numbers: 23 34 51 11 2 1 0 99 91 89 100 51
The second largest number is: 99
Few important tips about the program
1. We take a list from user and iterate over it to find the largest and second largest number.
2. If the new number is greater than the largest, then the the new number is the largest number and the previous largest number is now the second largest.
3. If the new number is just greater than the second largest but not the largest, then we only assign it to the second largest.
write a python program to find the second largest element in the list:
This wraps up session on python program to find 2nd largest number in a list or write a python program to find the second largest element in the list.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Devjeet Roy
Full Stack Web Developer & Blockchain Enthusiast
Page Views :
Published Date :
Jun 26,2022