Table of Contents
Introduction
In this section of python programming, we will understand the python code to print the second largest number in the given list. We have seen in earlier sections of programming that python provides in-built function max() to print the largest number.
Program
list = [10, 15, 20, 70] list1 = [1, 5, 7, 10] # Using sort() list_copy = list list.sort() print("The second largest number in the given list {0} is {1}". format(list_copy,list[-2])) # Find the largest number and delete the element list1_copy = set(list1) list1_copy.remove(max(list1_copy)) print("The second largest number in the given list {0} is {1}". format(list1, max(list1_copy)))
Output
Explanation
To find the second largest number in the lists we have used two methods:
- Sort the elements in the list and print the second element from the right. We are printing the element from right because by default the elements are sorted in ascending order.
- In the second method, first we created the set of list and find the largest number in the set with the help of max() function, and removed it. After this we printed the max number in the updated set.
So, the printed max number is the second largest number in the original given list.
0 Comments