Python Program to Find the Second Largest Number in a List

This article was created to cover some programs in Python that find and print the second largest number or element in a given list. Here is a list of programs covered in this article:

Find the second largest number in a list without using a function

The question is: write a Python program that finds the second largest element in a list using the for loop. Here is its answer:

nums = []
print("Enter 10 Elements (Numbers) for List: ")
for i in range(10):
  nums.append(int(input()))

large = nums[0]
for i in range(10):
  if large<nums[i]:
    large = nums[i]

secondLarge = nums[0]
for i in range(10):
  if secondLarge<nums[i]:
    if nums[i]!=large:
      secondLarge=nums[i]

print("\nSecond Largest Number is: ")
print(secondLarge)

Here is its sample run:

python find second largest number in list

Now supply the input, say 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 as ten numbers, then press the ENTER key to find and print the second largest number from the given list, as shown in the sample run given below:

find second largest number in list python

Find the second largest number in a list of given size

The question is: write a Python program that finds and prints the second largest number in a list of a given size. The program given below is the answer to this question. The end is used in this program to skip the insertion of an automatic newline.

nums = []
print(end="Enter the Size for List: ")
listSize = int(input())
print(end="Enter " +str(listSize)+ " Numbers for List: ")
for i in range(listSize):
  nums.append(int(input()))

large = nums[0]
for i in range(listSize):
  if large<nums[i]:
    large = nums[i]

secondLarge = nums[1]
for i in range(listSize):
  if secondLarge<nums[i] and nums[i]!=large:
    secondLarge=nums[i]

if large == secondLarge:
  print("\nSecond Largest Number doesn't exist!")
else:
  print("\nSecond Largest Number = " + str(secondLarge))

Here is its sample run with user input: 5 as the size of the list and 2, 1, 1, 1, 1 as the five numbers of the list:

python find second largest element in list

Find the second largest number in a list using max()

This program does the same job as the previous program. The only difference is that this program uses a predefined function named max() to find the maximum element in the list. I've removed the maximum element using the remove() method. And then again, using the max() method, print the second largest element, as shown in the program given below:

nums = []
print(end="Enter the Size for List: ")
listSize = int(input())
print(end="Enter " +str(listSize)+ " Numbers for List: ")
for i in range(listSize):
  nums.append(int(input()))

nums.remove(max(nums))
print("\nSecond Largest Number = " + str(max(nums)))

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!