Write a python program to print the second largest element in an array taken from the user. In this article, we are going to use multiple list methods to find the second largest element in an array
What is an array?
The array is just a list of similar datatype
for example a=[14,15,86,5,89,52] here all the elements are integer which denotes its an array
Algorithm
- Taking input how much element we want in the array
- Add the element one by one in the list and print the list
- Then print the second largest element of that array
Python program to print the second largest element of an array
a= int(input("enter the number of element want in a array:")) lst=[] for i in range(a): b=int(input("enter element: ")) lst.append(b) print("the entered list",lst) lst=set(lst) print("new array after removing duplicates",lst) lst=list(lst) lst.sort() print("second largest number in a array",lst[len(lst)-2])
Explanation of the Code
On-Line no:1 we took input from the user how many he want in the array
On-Line no:2 creating a list so that we can append element which user gives
On-Line no:3 iterating the loop for the number of times which user gives
On-Line no:4 taking input and converting into integer type
On-Line no:5 appending it to list we created before
On-Line no:6 printing the list we created
On-Line no:7 now using the set method to remove duplicate elements from the array
On-Line no:8 printing the new array we created using the set method
On-Line no:9 now converting back the set to list
On-Line no:10 sorting the list using sort method
On-Line no:11 printing the required element using len method and then accessing the element by index
Sample
We want an array of 4 elements and elements are 14, 45, 89, 78 and we want the second largest element that is 78
Output
In this module, we have learned how to print the second element of an array.