DAY 4 of PYTHON top 100 questions : from Basic to Advanced !!

DAY 4 of PYTHON top 100 questions : from Basic to Advanced !!

Write a Python program to find the second largest element in an array:-

x=[2,7,3,4,9,0,2]
x.sort()
print("The second largest element is",x[-2])

Output :

The second largest element is 7

This code sorts the list x in ascending order using the sort() method and then prints the second largest element of the sorted list using indexing with x[-2].

Here's a breakdown of how the code works:

  • x=[2,7,3,4,9,0,2]: This creates a list x with seven elements.

  • x.sort(): This sorts the elements of the list x in ascending order. After sorting, the list becomes [0, 2, 2, 3, 4, 7, 9].

  • print("The second largest element is",x[-2]): This prints the string "The second largest element is" followed by the second largest element of the sorted list x, which is 7.


If you are a beginner and want to know more about Python programming, you can read my Basics of Python blogs (From part 1 to part 15).


HAPPY LEARNING !!!