Open In App

Sort a list of objects by multiple attributes in Python

Last Updated : 13 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using lambda function

 

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:

Using itemgetter

 

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:

Using attrgetter

 

Time complexity: O(n log n)

Auxiliary space: O(1) because sorting id done in in-place.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads