Python Program to Find Second Largest Number in List

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

Find Second Largest Number in List without using Function

The question is, write a Python program that find second largest element in a list using 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 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 Second Largest Number in List of Given Size

The question is, write a Python program that find and prints second largest number in a list of given size. The program given below is the answer to this question. The end used in this program to skip 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 size of list and 2, 1, 1, 1, 1 as five numbers of list:

python find second largest element in list

Find Second Largest Number in List using max()

This program does the same job as of previous program. The only difference is, this program uses a predefined function named max() to find the maximum element in the list. I've removed the maximum element using remove() method. And then again using max() method, prints the second largest element like 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 »