Second Largest Number in Python

If you are interested to learn about the Python simple imputer module

When we have a lot of elements in our list, the thought of finding the highest or lowest element can come to our mind and Python has made it much easier for us. In this article, we shall how we can use to find the second largest number in Python from a list.

  1. Sorting the list and then print the second last number.
  2. Removing the maximum element.
  3. Finding the maximum element.
  4. Traversing the list.

Let us have a look at the first approach-

How do I find the second largest number in Python?Example –

#program to find the second largest number of list.
 # declaring the list. list_val = [20, 30, 40, 25, 10]
  # sorting the list. list_val.sort()
 #displaying the second last element of the list. print("The second largest element of the list is:", list_val[-2])

Sorting the list and then print the second last number

The following program illustrates how we can do it in Python-

Example –

#program to find the second largest number of list  
# declaring the list  
list_val = [20, 30, 40, 25, 10]  
# sorting the list  
list_val.sort()  
#displaying the second last element of the list  
print("The second largest element of the list is:", list_val[-2])  

Output:

The second largest element of the list is: 30

It’s time to go for the explanation part-

  1. We have declared the list from which we want to take out the second last element.
  2. After this, we used the sort method so that all the elements of our list are arranged in ascending order.
  3. Now we make use of negative indexing since the second-largest number will come at the second last position.

The second method is to obtain the second largest element of the list by removing the maximum element. Let us see how we can do it.

Removing the maximum element

Example –

#program to find the second largest number of list  
  
# declaring the list  
list_val = [20, 30, 40, 25, 10]  
  
# new_list is a set of list1  
res_list = set(list_val)  
  
#removing the maximum element  
res_list.remove(max(res_list))  
  
#printing the second largest element   
print(max(res_list))  

Output:

30

Explanation –

Let us understand what we have done in the above program-

  1. We have declared the list from which we want to take out the second last element.
  2. After this, we used the set method to take all the unique elements of the list.
  3. Now we make use of max() to get the maximum value from the list and then remove it.
  4. After this, we print the maximum of the resultant list which will give us the second-largest number.

In the third method, we will use for loop and find the second largest number from the list.

Example –

# declaring empty list  
list_val = []  
  
# user provides the number of elements to be added in the list  
num_list = int(input("Enter number of elements in list: "))  
  
  
for i in range(1, num_list + 1):  
    element = int(input("Enter the elements: "))  
    list_val.append(element)  
  
  
# sort the list  
list_val.sort()  
      
# print second largest element  
print("Second largest element is:", list_val[-2])  

Output:

Enter number of elements in list: 5

Enter the elements: 10

Enter the elements: 20

Enter the elements: 30

Enter the elements: 40

Enter the elements: 50
The second largest element is: 40

Explanation –

Let us have a glance at what we have done here-

  1. We have declared an empty list in which we will insert the elements.
  2. After this, we ask the user to provide us the number of elements we would like to add to our list.
  3. After this, we use the sort method so that all the elements of our list are arranged in ascending order.
  4. Now we make use of negative indexing since the second-largest number will come at the second last position.

Traversing the list

In the last program, we will traverse the list to find out the largest number and then make use of conditional statements to find the second largest number from the list.

The following program illustrates the same-

Example –

def calc_largest(arr):  
    second_largest = arr[0]  
    largest_val = arr[0]  
    for i in range(len(arr)):  
        if arr[i] > largest_val:  
            largest_val = arr[i]  
  
    for i in range(len(arr)):  
        if arr[i] > second_largest and arr[i] != largest_val:  
            second_largest = arr[i]  
  
    return second_largest  
print(calc_largest([20, 30, 40, 25, 10]))  

Output:

30

Explanation –

Let us understand what we have done in the above program-

  1. The first step is to create a function that checks the largest number from the list by traversing it.
  2. In the next for loop, we traverse the list again for finding the highest number but this time excludes the previous one since here our objective is to find the second largest function.
  3. Finally, we pass our list in the function.

Python Program 1

Look at the program to understand the implementation of the above-mentioned approach.

#second largest number in list

#function
def second_largest(list):
    list.sort()
    return list[-2]

#input of list
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
    e=int(input("Enter element of list "))
    li.append(e)

#smallest
print("second largest in ",li,"is")
print(second_largest(li))           

Copy

Enter size of list 5 Enter element of list 8 Enter element of list 3 Enter element of list 1 Enter element of list 9 Enter element of list 5 second largest in [8, 3, 1, 9, 5] is 8

To get the element at the second last index we have used negative indexing.

Approach 2: By Removing the maximum number from the list

In this approach, we will first find the maximum element in the list using built-in max() function. After getting the largest number we will delete it from the list using list.remove() which will remove the element from the list. Then again call the max() function to get the current maximum number in the list. This will be the second largest element in the list.

Algorithm

Follow the algorithm to understand the approach better

Step 1- Declare a function for finding the second largest number

Step 2- Use max() method and store the value returned by it in a variable

Step 3- Remove largest element from the list

Step 4- Again call max() and store the maximum element in the variable

Step 5- Return variable, this will be the second largest element

Step 6- Declare a list and take input or initialise values

Step 7- Call the function

Step 8- Print the value returned by the function

Python Program

Look at the program to understand the implementation of the above-mentioned approach.

#second largest number in list

#function
def second_largest(list):
    large= max(list)
    list.remove(large)
    large= max(list)
    return large


#input of list
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
    e=int(input("Enter element of list "))
    li.append(e)

#smallest
print("second largest in ",li,"is")
print(second_largest(li))            

Copy

Enter size of list 4 Enter element of list 9 Enter element of list 3 Enter element of list 6 Enter element of list 1 second largest in [9, 3, 6, 1] is 6

Approach 3: Brute-force approach

In this approach, we will follow the Brute-force approach. It is an exhaustive search algorithm where all the possible test solutions are checked for getting the optimal solution.

Algorithm

Follow the algorithm to understand the approach better

Step 1- Define a function to find the second largest number in the list

Step 2- Declare variables and store the maximum nd minimum between the first and the second element in the list

Step 3- Find length of list using len() and store in n

Step 4- Run a loop from 2 to n

Step 5- Check if list element is greater than maximum, if true update second maximum to maximum and set list element as maximum

Step 6- Else, if list element is greater than second maximum number then update list element as second maximum

Step 7- Return second maximum element

Step 8- Declare a list and take input or initialise values

Step 9- Call the function

Step 10- Print the value returned by the function

Python Program

Look at the program to understand the implementation of the above-mentioned approach.

#second largest number in list
#brute-force

#function
def second_largest(list):
    maximum= max(list[0],list[1])
    second_max= min(list[0],list[1])
    n=len(list)
    for i in range(2, n):
        if list[i]>maximum:
            second_max=maximum
            maximum=list[i]
        else:
            if list[i]>second_max:
                second_max=list[i]
            
    return second_max


#input of list
li=[]
n=int(input("Enter size of list "))
for i in range(0,n):
    e=int(input("Enter element of list "))
    li.append(e)

#smallest
print("second largest in ",li,"is")
print(second_largest(li))            

Copy

Enter size of list 7 Enter element of list 3 Enter element of list 9 Enter element of list 12 Enter element of list 45 Enter element of list 2 Enter element of list 3 Enter element of list 0 second largest in [3, 9, 12, 45, 2, 3, 0] is 12

Conclusion

In this tutorial, we have discussed different approaches for finding the second largest element in the list. We have discussed three approaches- using sorted list elements to print the second last element, by removing the maximum element from the list and then finding the largest in the list and lastly, we have used the Brute-force approach to get the second largest element in the list.

Second Largest Number in Python
Show Buttons
Hide Buttons