Python program to find second largest number in a list

This article will learn to find the second largest number in a list using the python program.

So, we find the second largest number in a list using 3 different methods:

  1. By using sorting 
  2. By using max() function
  3. By using the traversal. 


By using sorting

Explanation

  1. First, we sort the list in ascending order.
  2. Then we print the second last element because we know that the second last element is the second largest element in ascending order.
  3. Then we print the second largest element.

Program

1
2
3
4
5
6
7
8
# list
list = [12, 13, 55, 21, 8]

# arrange the list in ascending order by using sort() func.
list.sort()

# print the last second element of the list
print("The second-largest number is:",list[-2])

Output

The second-largest number is: 21


By using max() function

Explanation

First, we find the largest elements using the max() function.

Then we will remove the largest element.

Then again we find the largest elements using the max() function.

Then this largest element is the second largest element.

So, lastly, we print these elements as the second largest element.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# list
list = [12, 13, 55, 21, 8]

# find the largest number using max() function
maximum = max(list)
# then remove this largest number
list.remove(maximum)

# then again find the largest number and this number is the second largest number
second_largest = max(list) 

# print the last second element of the list
print("The second-largest number is:",second_largest)

Output

The second-largest number is: 21


By using the traversal

Explanation

  1. First, we assume that the second largest and largest element is the first element.
  2. Then we find the largest elements using for loop.
  3. And then we find the second largest element by checking that these elements are not equal to the largest element using for loop.
  4. Then we print the second largest element.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# list
list = [12, 13, 55, 21, 8]

# assumption
second_largest = list[0]
largest = list[0]

# first find the largest number
for i in range(0, len(list)):
     if list[i] > largest:
            largest = list[i]
 
# then we find the second largest number
for i in range(0, len(list)):
    if list[i] > second_largest and list[i] != largest:
        second_largest = list[i]

# print the last second element of the list
print("The second-largest number is:",second_largest)

Output

The second-largest number is: 21

Next Post Previous Post
No Comment
Add Comment
comment url