How to Sort List of Tuples by Last Element in Python

In this tutorial, we will learn how to program "How to Sort a List of Tuples by the Last Element in Python". The objective is to sort a list of tuples by their last elements. This tutorial will guide you step by step through the process of sorting tuples based on their last element. 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 of tuples by their last element. 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.
  1. def last(n):
  2.     return n[-1]
  3.  
  4. def sort_tuples(tuples):
  5.     return sorted(tuples, key=last)
  6.  
  7. while True:
  8.     print("\n============== Sort List of Tuples by Last Element ==============\n")
  9.  
  10.    
  11.     a = input("Enter a list of tuples (e.g., [(1, 2), (3, 1), (5, 0)]): ")
  12.  
  13.     try:
  14.        
  15.         tuples_list = eval(a)
  16.  
  17.      
  18.         if isinstance(tuples_list, list) and all(isinstance(t, tuple) for t in tuples_list):
  19.             print("\nSorted list of tuples:")
  20.             print(sort_tuples(tuples_list))
  21.         else:
  22.             print("Invalid input! Please enter a list of tuples like [(1,2),(3,1)].")
  23.     except:
  24.         print("Invalid format! Please enter valid Python-style tuples.")
  25.  
  26.    
  27.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  28.     if opt == 'no':
  29.         print("Exiting program...")
  30.         break
  31.     elif opt != 'yes':
  32.         print("Invalid choice. Exiting program...")
  33.         break

This Python program sorts a list of tuples based on the last element of each tuple. It asks the user to input tuples in Python list format (e.g., `[(1, 2), (3, 1), (5, 0)]`), then uses the built-in `sorted()` function with a custom key function (`last()`) to perform the sorting. The program validates the input to ensure it’s a proper list of tuples and displays the sorted result. It repeats the process until the user decides to exit.

Output:

There you have it we successfully created How to Sort List of Tuples by Last 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

Python Tutorials