How to Sort a List According to the Second Element in a Sublist in Python
In this tutorial, we will learn how to program "How to Sort a List According to the Second Element in a Sublist in Python". The objective is to sort a list by the second element of each sublist. This tutorial will guide you step by step through the process of sorting a list based on a specific condition. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving skills and improve your coding abilities.
This topic is straightforward and easy to understand. Simply follow the instructions, and you’ll complete it with ease. The program will guide you step by step through the process of sorting a list by the second element of each sublist. So, let’s dive into the coding process!
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.- while True:
- print("\n=========== Sort a List According to the Second Element in a Sublist ===========\n")
- # Get number of sublists
- n = int(input("Enter number of sublists: "))
- a = []
- for i in range(n):
- name = input(f"Enter name for element {i+1}: ")
- value = int(input(f"Enter number for {name}: "))
- a.append([name, value])
- # Bubble sort by second element
- for i in range(len(a)):
- for j in range(0, len(a) - i - 1):
- if a[j][1] > a[j + 1][1]:
- a[j], a[j + 1] = a[j + 1], a[j]
- print("\nSorted list according to the second element:")
- print(a)
- # Ask if the user wants to repeat
- opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
- if opt == 'no':
- print("Exiting program...")
- break
- elif opt != 'yes':
- print("Invalid choice. Exiting program...")
- break
This Python program sorts a list of sublists based on the second element in each sublist. It first asks the user how many sublists they want to create, then takes input for each sublist consisting of a name and a number. Using the Bubble Sort algorithm, the program arranges the sublists in ascending order according to their numeric values (the second elements). After sorting, it displays the organized list. The program runs continuously until the user decides to exit, making it simple and interactive for repeated sorting tasks.
Output:
There you have it we successfully created How to Sort a List According to the Second Element in a Sublist in 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