Signup/Sign In

Python Program To Sort a list of tuples by second Item

In this, tutorial We have one list of tuples in, and we need to sort it by the index of sorting, which is the second component of the tuple. When a list of tuples is sorted by the second value, the tuples' positions in the list are rearranged so that the second values of the tuples are in ascending order.

So, We are going to sort a list of tuples with the help of three methods. Let us have a look at the examples to understand the input-output format:

Input List = [('shubh', 2), ('sinha', 4), ('tonight', 8), ('study', 6)]

Outpt List = [('shubh', 2), ('sinha', 4), ('study', 6), ('tonight', 8)]

Input List = [(200, 6), (100, 3), (400, 12), (300, 9)]

Output List = [(100, 3), (200, 6), (300, 9), (400, 12)]

To execute this task, we can follow multiple approaches, some are discussed below:

  1. Using sort() method

  2. Using sorted() method

  3. Using binary search method

We will discuss all these approaches in detail separately.

Approach 1: Using sort() method

Python has various built-in sorting functions. When utilizing the sorting techniques, we must provide a method that swaps the element to the second member of the tuple.

Algorithm

  1. Initialize Tuple List.
  2. Define the function Sort(For Sorting Tuple)
  3. Set the key to sorting using the second element
  4. Use sublist lambda
  5. Print the result

Program

In this program, the actual content of the tuple is changed while sorting with this method. The sort() function uses the default comparisons operator between items to sort the components of a list in ascending or descending order. Instead of using the default operator, use the key argument to give the function name to be used for comparison.

#tuple list
tuple = [(200, 6), (100, 3), (400, 12), (300, 9)]
print("Orignal Tuple List :" ,tuple)
#function
def Sort(tuple): 
    # Sorts in Ascending order 
    tuple.sort(key = lambda a: a[1]) 
    return tuple 

# printing the sorted list of tuples
print("Sorted Tuple List:" ,Sort(tuple))


Orignal Tuple List : [('shubh', 2), ('sinha', 4), ('tonight', 8), ('study', 6)]
Sorted Tuple List: [('shubh', 2), ('sinha', 4), ('study', 6), ('tonight', 8)]

Approach 2: Using sorted() functions

The Sorted() function sorts a list and always returns a list with sorted entries, without changing the original order. In this program, we will use a sorted function similar to a sort function but this function comes with three parameters i.e., Iterable, keys, and reverse. Let us have a look at the algorithm followed by code:

Algorithm

  1. Initializing List
  2. Print the original List
  3. Define the function Sort(For Sorting Tuple)
  4. Set the key to sorting using the second element
  5. Use sublist lambda
  6. Print the result

Program

The sorted() method returns a sorted list of the iterable object that was passed in. You may choose whether to sort the results in ascending or descending order. Numbers are ordered numerically, whereas strings are arranged alphabetically.

# Tuple
tuple = [(200, 6), (100, 3), (400, 12), (300, 9)]
print("Orignal List: ", tuple)
# Function to sort 
def Sort(tuple): 
    # reverse = None (Sorts in Ascending order) 
    return(sorted(tuple, key = lambda a: a[1]))  
 
# sorted list of tuples
print("Sorted List: ", Sort(tuple)) 


Orignal List: [(200, 6), (100, 3), (400, 12), (300, 9)]
Sorted List: [(100, 3), (200, 6), (300, 9), (400, 12)]

Approach 3: Using Binary Search Operation

We have a list of tuples in our program, and we need to sort it by the index of sorting, which is the second item in the tuple. We'll effectively utilize a sorting method, except instead of utilizing the list's first value, we'll use the tuple's second member.

Algorithm

  1. Initializing List
  2. Print the original List
  3. Define the length of the tuple list
  4. Sorting using binary function
  5. Print the result

Program

In this program, sorting is done using the binary sorting approach. The second member of the tuple will be used as an index for sorting the list.

# Creating a new tuple 
tuple =  [('shubh', 2), ('sinha', 4), ('tonight', 8), ('study', 6)]
print("Orignal list : ", str(tuple))

# Sorting the list of tuples using second item 
Len = len(tuple)
for i in range(0, Len):
    for j in range(0, (Len - i - 1)):
        if(tuple[j][1] > tuple[j+1][1]):
            temp = tuple[j]
            tuple[j] = tuple[j+1]
            tuple[j+1] = temp

#  sorted list 		
print("Sorted List : ", str(tuple))


Orignal list : [('shubh', 2), ('sinha', 4), ('tonight', 8), ('study', 6)]
Sorted List : [('shubh', 2), ('sinha', 4), ('study', 6), ('tonight', 8)]

Conclusion

In this tutorial, we have seen two approaches to sort a list of tuples by the second Item. The first approach is by using the sort() method which sorts a list and always returns a list with sorted entries, without changing the original order and the second approach is by using a sorted method which is similar to the sort method and the last method is by using the binary search method in which we have a list of tuples in our program, and we need to sort it by the index of sorting, which is the second item in the tuple.