How to Sort Sublists Based on Second Element in Python
In this tutorial, we will learn how to program "How to Sort Sublists Based on the Second Element in Python." The objective is to sort sublists based on their second element. This tutorial will guide you step by step through the process of sorting a sublist. 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 abilities and improve your coding skills.
This topic is straightforward to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of sorting the sublists. 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 Sublists in Python Based on Second Element ==============\n")
- a = []
- n = int(input("Enter number of sublists: "))
- for i in range(n):
- name = input(f"Enter name/label for sublist {i+1}: ")
- value = int(input(f"Enter numeric value for sublist {i+1}: "))
- a.append([name, value])
- # Bubble sort based on the 2nd element
- for i in range(len(a)):
- for j in range(0, len(a) - i - 1):
- if a[j][1] > a[j + 1][1]:
- temp = a[j]
- a[j] = a[j + 1]
- a[j + 1] = temp
- print("\nSorted list:", a)
- 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 program sorts a list of sublists based on the second element of each sublist. The user is prompted to enter the number of sublists and provide a name/label and a numeric value for each. It uses a simple bubble sort algorithm to order the sublists in ascending order according to their numeric values. After sorting, the program displays the sorted list and allows the user to repeat the process or exit.
Output:

There you have it we successfully created How to Sort Sublists Based on Second Element 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