How to Find 2nd Largest Number in a List in Python


In this example we will show how to find the second largest number in a list using the bubble sort algorithm.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def bubbleSort(n):
    for i in range(len(n)):  
        for j in range(len(n) - i - 1): 
            if n[j] > n[j + 1]:
                n[j], n[j + 1] = n[j + 1], n[j]
    return n

b = input('Please input a number or input 'q' to quit: ')
if b == "q":
    print("Quit")
else:
    a = []
    while b != "q":
        a.append(int(b))
        b = input('Please input a number or input 'q' to quit: ')
    print("The second largest number is: ", bubbleSort(a)[-2])

Output:

Please input a number or input 'q' to quit: 15
Please input a number or input 'q' to quit: 20
Please input a number or input 'q' to quit: 26
Please input a number or input 'q' to quit: 18
Please input a number or input 'q' to quit: 19
Please input a number or input 'q' to quit: 10
Please input a number or input 'q' to quit: q
The second largest number is:  20
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments