Python | Sort tuple list on basis of difference of elements

Python | Sort tuple list on basis of difference of elements

To sort a list of tuples based on the difference of their elements, you can use Python's sorted() function with a custom key function. This tutorial will guide you through this task.

Step 1: Understand the Problem

Given a list of 2-tuples:

tuples_list = [(5, 3), (8, 6), (2, 7)] 

If you want to sort this list based on the difference between the two elements of each tuple, the result would be:

[(5, 3), (8, 6), (2, 7)] 

The differences are 2, 2, and 5, respectively.

Step 2: Define the Key Function

Define a lambda function that calculates the difference between the two elements of a tuple.

diff_key = lambda x: abs(x[0] - x[1]) 

This function computes the absolute difference between the first and the second element of the tuple.

Step 3: Use the sorted() Function

Now, use the sorted() function with the key function you just defined:

sorted_tuples = sorted(tuples_list, key=diff_key) 

Full Code:

Here's the complete code:

tuples_list = [(5, 3), (8, 6), (2, 7)] # Define the key function diff_key = lambda x: abs(x[0] - x[1]) # Sort the list of tuples sorted_tuples = sorted(tuples_list, key=diff_key) print(sorted_tuples) 

Output:

[(5, 3), (8, 6), (2, 7)] 

Recap:

To sort a list of tuples based on the difference of their elements:

  1. Understand that you'll be sorting based on the absolute difference between elements of the tuple.
  2. Define a key function to compute this difference.
  3. Use the sorted() function with the key function to sort the list of tuples.

More Tags

csv ng2-file-upload release galleryview client-side-validation nuget font-face jar hyperledger sql-query-store

More Programming Guides

Other Guides

More Programming Examples