Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Multiple Column Sort in Tuples

  • Last Updated : 06 Jul, 2021

Sometimes, while working with records, we can have a problem in which we need to perform sort operation on one of the columns, and on other column, if equal elements, opposite sort. This kind of problem can occur as application in many domains such as web development. Lets discuss certain ways in which this problem can be solved.

Input : test_list = [(6, 7), (6, 5), (6, 4), (7, 10)] 
Output : [(7, 10), (6, 4), (6, 5), (6, 7)]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Input : test_list = [(10, 7), (8, 5)] 
Output : [(10, 7), (8, 5)] 
 



Method #1 : Using sorted() + lambda 
The combination of above functions can offer one of the ways to solve this problem. In this, we perform sort using sorted() and order and column manipulation is handled by lambda function.

Python3




# Python3 code to demonstrate working of
# Multiple Column Sort in Tuples
# Using sorted() + lambda
 
# initializing list
test_list = [(6, 7), (6, 5), (1, 4), (8, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Multiple Column Sort in Tuples
# Using sorted() + lambda
res = sorted(test_list, key = lambda sub: (-sub[0], sub[1]))
 
# printing result
print("The sorted records : " + str(res))
Output : 
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]

 

 Method #2 : Using itemgetter() + sorted() 
This is yet another way in which this task can be performed. In this, we perform the task required for lambda function using itemgetter().

Python3




# Python3 code to demonstrate working of
# Multiple Column Sort in Tuples
# Using itemgetter() + sorted()
from operator import itemgetter
 
# initializing list
test_list = [(6, 7), (6, 5), (1, 4), (8, 10)]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Multiple Column Sort in Tuples
# Using itemgetter() + sorted()
res = sorted(test_list, key = itemgetter(1))
res = sorted(res, key = itemgetter(0), reverse = True)
 
# printing result
print("The sorted records : " + str(res))
Output : 
The original list is : [(6, 7), (6, 5), (1, 4), (8, 10)]
The sorted records : [(8, 10), (6, 5), (6, 7), (1, 4)]

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!