Python | sort list of tuple based on sum
Last Updated :
11 Apr, 2023
Given, a list of tuple, the task is to sort the list of tuples based on the sum of elements in the tuple.
Examples:
Input: [(4, 5), (2, 3), (6, 7), (2, 8)]
Output: [(2, 3), (4, 5), (2, 8), (6, 7)]
Input: [(3, 4), (7, 8), (6, 5)]
Output: [(3, 4), (6, 5), (7, 8)]
# Method 1: Using bubble sort Using the technique of Bubble Sort to we can perform the sorting. Note that each tuple is an element in the given list. Access the elements of each tuple using the nested loops. This performs the in-place method of sorting. The time complexity is similar to the Bubble Sort i.e. O(n^2).
Python3
# Python code to sort list of tuple based on sum of element in tuple.
# Input list initialisation
Input = [(4, 5), (2, 3), (6, 7), (2, 8)]
print("The original list of tuple is ")
print(Input)
# getting length of list of tuples
lst = len(Input)
# Bubble sort
for i in range(lst):
for j in range(lst-i-1):
if (Input[j][0]+Input[j][1]) > (Input[j+1][0]+Input[j+1][1]):
Input[j], Input[j+1] = Input[j+1], Input[j]
# print output
print("\nThe answer is")
print(Input)
Output:
The original list of tuple is
[(4, 5), (2, 3), (6, 7), (2, 8)]
The answer is
[(2, 3), (4, 5), (2, 8), (6, 7)]
# Method 2: Using sorted() method This is the most basic efficient and short method to achieve the solution to this task. In this, we pass lambda as key to the list of tuples.
Python3
# Python code to sort list of tuple based on sum of element in tuple.
# Input list initialisation
Input = [(4, 5), (2, 3), (6, 7), (2, 8)]
print("The original list of tuple is ")
print(Input)
# Passing lambda as key to sort list of tuple
print("\nThe answer is")
print(sorted(Input, key = lambda x:x[0] + x[1]))
Output:
The original list of tuple is
[(4, 5), (2, 3), (6, 7), (2, 8)]
The answer is
[(2, 3), (4, 5), (2, 8), (6, 7)]
# Method 3: Using sort() method While sorting via this method the actual content of the tuple is changed, and just like the bubble sort, the in-place method of the sort is performed.
Python3
# Python code to sort list of tuple based on sum of element in tuple.
# Input list initialisation
Input = [(4, 5), (2, 3), (6, 7), (2, 8)]
print("The original list of tuple is ")
print(Input)
# Passing lambda as key to sort list of tuple
Input.sort(key = lambda x: x[0] + x[1])
# Printing output
print("\nThe answer is")
print(Input)
Output:
The original list of tuple is
[(4, 5), (2, 3), (6, 7), (2, 8)]
The answer is
[(2, 3), (4, 5), (2, 8), (6, 7)]
Approach#4: Using sum()
Create a new list of tuples where the first element is the sum of each tuple and the second element is the original tuple. Sort the new list based on the first element (the sum). Extract and return only the original tuples from the sorted list.
Algorithm
1. Define a function that takes a list of tuples as input.
2. Create a new list of tuples where the first element is the sum of each tuple and the second element is the original tuple.
3. Sort the new list based on the first element (the sum).
4. Extract and return only the original tuples from the sorted list.
Python3
def sort_tuples_by_sum(lst):
# create a new list of tuples where the first element is the sum of each tuple and the second element is the original tuple
sum_tuples = [(sum(t), t) for t in lst]
# sort the new list based on the first element (the sum)
sorted_sum_tuples = sorted(sum_tuples, key=lambda x: x[0])
# extract and return only the original tuples from the sorted list
return [t[1] for t in sorted_sum_tuples]
# example usage
lst = [(4, 5), (2, 3), (6, 7), (2, 8)]
print(sort_tuples_by_sum(lst))
lst = [(3, 4), (7, 8), (6, 5)]
print(sort_tuples_by_sum(lst))
Output[(2, 3), (4, 5), (2, 8), (6, 7)]
[(3, 4), (6, 5), (7, 8)]
Time Complexity: O(nlogn), where n is length of list
Space Complexity: O(n)
Similar Reads
Position Summation in List of Tuples - Python
Position Summation in List of Tuples refers to the process of calculating the sum of elements at the same positions across multiple tuples in a list. This operation involves adding up the corresponding elements from each tuple.For example, consider the list of tuples [(1, 6), (3, 4), (5, 8)]. The go
3 min read
Create a List of Tuples in Python
The task of creating a list of tuples in Python involves combining or transforming multiple data elements into a sequence of tuples within a list. Tuples are immutable, making them useful when storing fixed pairs or groups of values, while lists offer flexibility for dynamic collections. For example
3 min read
Python | Sort a tuple by its float element
In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting. Examples: Input : tuple = [('lucky', '18.265'), ('nikhil', '1
3 min read
Python - Sort list of list by specified index
When working with a list of lists, we often need to sort the inner lists based on the values at a specific index. Sorting by a specified index is useful in the custom ordering of multidimensional data. In this article, we will explore different ways to sort a list of lists by a specified index in Py
3 min read
Ways to Iterate Tuple List of Lists - Python
In this article we will explore different methods to iterate through a tuple list of lists in Python and flatten the list into a single list. Basically, a tuple list of lists refers to a list where each element is a tuple containing sublists and the goal is to access all elements in a way that combi
3 min read
How to iterate through list of tuples in Python
In Python, a list of tuples is a common data structure used to store paired or grouped data. Iterating through this type of list involves accessing each tuple one by one and sometimes the elements within the tuple. Python provides several efficient and versatile ways to do this. Letâs explore these
2 min read
Convert Tuple to List in Python
In Python, tuples and lists are commonly used data structures, but they have different properties:Tuples are immutable: their elements cannot be changed after creation.Lists are mutable: they support adding, removing, or changing elements.Sometimes, you may need to convert a tuple to a list for furt
2 min read
Python | SymPy Partition.sort_key() method
Partition.sort_key() : sort_key() is a sympy Python library function that returns canonical key which can be used for string. This ordering of canonical key is based on the size and the elements of the partition whose ties are broken with the rank. Syntax : sympy.combinatorics.partitions.Partition.s
1 min read
Python | Get sum of tuples having same first value
Given a list of tuples, the task is to sum the tuples having the same first value. Examples: Input: [(1, 13), (2, 190), (3, 82), (1, 12)] Output: [(1, 25), (2, 190), (3, 82)]Input: [(1, 13), (1, 190), (3, 25), (1, 12)] Output: [(1, 215), (3, 25)] Let us discuss the different ways we can do this task
6 min read
How toGet First and Last Elements from a Tuple in Python
Tuples are immutable sequences in Python that can store a collection of items. Often, we might need to the retrieve the first and last elements from the tuple. In this article, we'll explore how to achieve this using the various methods in Python. Get First and Last Elements from a Tuple Using Index
2 min read