In this article, we are going to learn how to sort a list by multiple attributes with Python.
Introduction
Python is a dynamically typed language that offers numerous data types, such as list, tuple, set, dictionary, etc. and sorting is the most commonly used operation on any data structures such as list in Python. To perform this we can use the sorted() function in Python, but the catch in it is that we can sort the list by only one attribute through it. Thus, if we want to sort a list through multiple attributes, there are various other ways to achieve it. which can be discuss in this article.
Sorting a list by multiple attributes
The use of multiple attributes while sorting is that if any row name is the same in the first column, then it will look for the second column and arrange the data according to it. If the data in the second column is also a column for those particular rows, then it will jump to the third column and arrange the particular rows according to that data.
Methods to sort a list by multiple attributes with Python
Method 1: Using lambda function
In this method, we use the sorted function with the lambda function, rather than using the sorted function directly. The lambda function gives the user the freedom to sort by multiple attributes.
Syntax:
sorted(defined_list, key = lambda x: (x[column_number_1], x[column_number_2]))
Stepwise Implementation:
Step 1: First of all, we need to define the list and declare it in a variable.
list_defined=[ #Define the list ]
Step 2: Now, sort the list using the sorted function. Inside the sorted function, declare the list variable along with the lambda function with the column numbers through which you want to sort the list.
sorted_list=sorted(defined_list, key = lambda x: (x[column_number_1], x[column_number_2]))
Step 3: Finally, print the sorted list.
print(sorted_list)
Example:
In this example, we have declared a list and then sorted the list using the second and third columns. This sorting is achieved using the sorted function with the lambda function as an argument in it. Here, we saw that the data 'Arun' is the same for two rows, row 0 and row 2 in column 1. Thus, it will look for those particular rows, i.e., row 0 and row 2 in column 2, and arrange those rows according to column 2. Finally, we got to know that row 2 will have higher precedence than row 0.
Python
# Python program to sort a list by multiple
# attributes using lambda function
# Define the list and declare in variable
list_defined=[[1, 'Arun', 'Computer', 50000],
[2, 'Akash', 'Physics', 20000],
[3, 'Arun', 'Chemistry', 30000]]
# Sort the list using sorted() function
# and lambda function for multiple attributes
sorted_list = sorted(list_defined, key = lambda x: (x[1], x[2]))
# Print the sorted list
print(sorted_list)
Further, run the Python code using the following command in the terminal–
Python run.py
Output:
Time complexity: O(n log n), where n is the number of elements in the list.
Space complexity: O(n), as a new list is created to store the sorted elements, which takes up O(n) space.
Method 2: Using itemgetter
In this way, we use the sorted function with the itemgetter, rather than using the sorted function directly. The itemgetter gives the user the freedom to sort by multiple attributes. The itemgetter function takes an item or pointer to that item.
Syntax:
print(sorted(defined_list, key = operator.itemgetter(column_number_1, column_number_2)))
Stepwise Implementation:
Step 1: First of all, import the required libraries, i.e., the operator.
import operator
Step 2: Now, we need to define the list and declare it in a variable.
list_defined=[ #Define the list ]
Step 3: Now, sort the list using the sorted function. Inside the sorted function, declare the list variable along with the itemgetter with the column numbers through which you want to sort the list.
sorted_list=sorted(defined_list, key = operator.itemgetter(column_number_1, column_number_2))
Step 4: Finally, print the sorted list.
print(sorted_list)
Example:
In this example, we have sorted the list using the second and third columns. This sorting is achieved using the sorted function with the itemgetter as an argument in it. Here, we saw that the data 'Arun' is the same for two rows, row 0 and row 2 in column 1. Thus, it will look for those particular rows, i.e., row 0 and row 2 in column 2, and arrange those rows according to column 2. Finally, we got to know that row 2 will have higher precedence than row 0.
Python
# Python program to sort a list by multiple
# attributes using itemgetter
# Import the library operator
import operator
# Define the list and declare in variable
list_defined=[[1, 'Arun', 'Computer', 50000],
[2, 'Akash', 'Physics', 20000],
[3, 'Arun', 'Chemistry', 30000]]
# Sort the list using sorted() function
# and itemgetter for multiple attributes
sorted_list=sorted(list_defined, key = operator.itemgetter(1, 2))
# Print the sorted list
print(sorted_list)
Further, run the Python code using the following command in the terminal–
Python run.py
Output:
Time complexity: O(n log n), where n is the number of elements in the list.
Space complexity: O(n), as a new list is created to store the sorted elements, which takes up O(n) space.
Method 3: Using attrgetter
In this way, we use the sorted function with the attrgetter, rather than using the sorted function directly. The attrgetter gives the user the freedom to sort by multiple attributes. The attrgetter fetches the whole column through the column name.
Syntax:
print(defined_list.sort(key=attrgetter('#column_heading_1', '#column_heading_2')))
Stepwise Implementation:
Step 1: First of all, import the required libraries, i.e., the operator.
import operator
Step 2: Now, we need to define the class for setting column heading and returning object orientation in string format.
class String_representation:
Step 3: Then, call the constructor to set the column heading for each column.
def __init__(self, column_heading_1, column_heading_2):
self.column_heading_1 = column_heading_1
self.column_heading_2 = column_heading_2
Step 4: Later on, return the object orientation in string format using the __repr__() function.
def __repr__(self):
return '[' + self.column_heading_1 + ', ' + self.column_heading_2 + ']'
Step 5: Further, call the class and declare the values for the columns.
list_defined = [
String_representation(column_1_value, column_2_value ),
String_representation(column_1_value, column_2_value),
String_representation(column_1_value, column_2_value)
]
Step 6: Now, sort the list using the sorted function. Inside the sorted function, declare the list variable along with the attrgetter with the column headings through which you want to sort the list.
list_defined.sort(key=attrgetter('#column_heading_1', '#column_heading_2'))
Step 7: Finally, print the sorted list.
print(list_defined)
Example:
In this example, we have sorted the list using the second and third columns. This sorting is achieved using the sorted function with the attrgetter as an argument in it. Here, we saw that the data 'Arun' is the same for two rows, row 0 and row 2 in column 'name'. Thus, it will look for those particular rows, i.e., row 0 and row 2 in column 2, and arrange those rows according to column 'subject'. Finally, we got to know that row 2 will have higher precedence than row 0.
Python
# Python program to sort a list by multiple
# attributes using attrgetter
# Import the library operator
import operator
# Define the class
class String_representation:
# Call the constructor to set column heading for each column
def __init__(self, roll_no, name, subject, fees):
self.roll_no = roll_no
self.name = name
self.subject = subject
self.fees = fees
# Return the object orientation in string format
def __repr__(self):
return '[' + str(self.roll_no) + ', ' + self.name + ', ' +self.subject+ ', ' +str(self.fees)+ ']'
# Call the class function and declare the values
list_defined = [
String_representation(1, 'Arun', 'Computer', 50000),
String_representation(2, 'Akash', 'Physics', 20000),
String_representation(3, 'Arun', 'Chemistry', 30000)
]
# Sort the list using sorted() function
# and attrgetter for multiple attributes
list_defined.sort(key=operator.attrgetter('name', 'subject'))
# Print the sorted list
print(list_defined)
Further, run the Python code using the following command in the terminal –
Python run.py
Output:
Time complexity: O(n log n)
Auxiliary space: O(1) because sorting id done in in-place.
Similar Reads
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
Python List sort() Method The sort() method in Python is a built-in function that allows us to sort the elements of a list in ascending or descending order and it modifies the list in place which means there is no new list created. This method is useful when working with lists where we need to arranged the elements in a spec
3 min read
How to compare JSON objects regardless of order in Python? JSON is Java Script Object Notation. These are language independent source codes used for data exchange and are generally lightweight in nature. It acts as an alternative to XML. These are generally texts which can be read and written easily by humans and it is also easier for machines to parse JSON
2 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 Tuples in Increasing Order by any key Given a tuple, sort the list of tuples in increasing order by any key in tuple. Examples: Input : tuple = [(2, 5), (1, 2), (4, 4), (2, 3)] m = 0 Output : [(1, 2), (2, 3), (2, 5), (4, 4)] Explanation: Sorted using the 0th index key. Input : [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 Output : So
3 min read
Ways to sort list of dictionaries by values in Python â Using itemgetter In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article.In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently ut
2 min read