Write a Python Program to Find The Second Largest Number in a List

Given a list of integers you have to find the second largest number in a list,  in order to solve this you have to keep finding the first largest and second largest number and compare it with all the items present in the list.

 

Write a Python Program to Find The Second Largest Number in a List

 



Write a python program to find the second largest number in a list

Let's take a variable length and ask a user to enter the length and then take an empty list and ask a user to enter all the numbers present in the list using a for loop and make a Python list of numbers.

length = int(input("Enter List Length  : "))
numbers_list = []
for _ in range(length):
   temp = int(input("Enter List Item : "))
   numbers_list.append(temp)



Assume the first largest and second largest number carbon first element of a list is the first number having index 0 in a list.  use the following to iterate all the items in a list.

Check if Item is greater than first largest  if this is true,  second largest will became the first largest, first largest will become the item  

Using the else if part check if item is greater than the second largest and item not  equal to the first largest then second largest will become the item value.

first_largest = numbers_list[0]
second_largest = numbers_list[0]
for item in numbers_list:
   if item > first_largest:
       second_largest, first_largest = first_largest, item
   elif item > second_largest and item != first_largest:
       second_largest = item




Once the for loop is completed the variables will store first largest and the second largest numbers of a list finally  print it.

print("Largest Element in List is : ", second_largest)




Final program
====================

length = int(input("Enter List Length  : "))
numbers_list = []
for _ in range(length):
   temp = int(input("Enter List Item : "))
   numbers_list.append(temp)

first_largest = numbers_list[0]
second_largest = numbers_list[0]

for item in numbers_list:
   if item > first_largest:
       second_largest, first_largest = first_largest, item
   elif item > second_largest and item != first_largest:
       second_largest = item

print("Largest Element in List is : ", second_largest)




Output
===============

Enter List Length  : 5
Enter List Item : 1
Enter List Item : 2
Enter List Item : 4
Enter List Item : 3
Enter List Item : 5
Largest Element in List is :  4




OUTPUT
=====================

Enter List Length  : 10
Enter List Item : 56
Enter List Item : 78
Enter List Item : 34
Enter List Item : 90
Enter List Item : 93
Enter List Item : 23
Enter List Item : 76
Enter List Item : 67
Enter List Item : 89
Enter List Item : 45
Largest Element in List is :  90




Conclusion:  Run the program by giving different  list length,  and providing list of numbers as a input  see the difference,  comment down below If you have any queries

Post a Comment

0 Comments