How to Find Second Largest Number in a List using Python

In this tutorial, we will program 'How to Find the Second Largest Number in a List using Python'. We will learn how to extract the second largest number from a list. The objective is to enable you to efficiently identify and retrieve the second largest number in a list. I will provide a sample program to demonstrate the actual coding process in this tutorial.

This topic is very easy to understand. Just follow the instructions I provide, and you can do it yourself with ease. The program I will show you covers the basics of programming for getting the second largest number in a list. I will do my best to provide you with a simple method for obtaining the second largest number. So, let's start with the coding.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. list1 = [6, 2, 12, 45, 87, 34, 23, 125, 87]
  2.  
  3. list2 = list(set(list1))
  4.  
  5. list2.sort()
  6.  
  7.  
  8. ret = False
  9.  
  10.  
  11. while True:
  12. print("\n================== Find Second Largest Number in a List ==================\n\n")
  13.  
  14. print("My current list: ", list1)
  15.  
  16. print("The Second largest element is:", list2[-2])
  17.  
  18. opt = input("\nDo you want to try again?(yes/no): ")
  19.  
  20. if opt.lower() == 'yes':
  21. ret=False
  22. elif opt.lower() == 'no':
  23. ret=True
  24. print("Exiting program....")
  25.  
  26. else:
  27. print("Please enter yes/no:")
  28. break
  29.  
  30. if ret == False:
  31. continue

This script identifies the second largest number in a predefined list. It first removes duplicate elements and sorts the list in ascending order. In an infinite loop, it displays the original list and prints the second largest number from the sorted list. The user is prompted to decide whether to repeat the operation or exit the program. If the user chooses to repeat, the loop continues; otherwise, the program exits.

Output:

The How to Find Second Largest Number in a List using Python source code that I provide can be download below. Please kindly click the download button.

There you have it we successfully created How to Find Second Largest Number in a List using Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Tags

Add new comment