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
Get index in the list of objects by attribute in Python
In this article, we'll look at how to find the index of an item in a list using an attribute in Python. We'll use the enumerate function to do this. The enumerate() function produces a counter that counts how many times a loop has been iterated. We don't need to import additional libraries to utili
2 min read
How to Get a List of Class Attributes in Python?
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to
4 min read
How to Print Object Attributes in Python
In Python, objects are the cornerstone of its object-oriented programming paradigm. An object is an instance of a class, and it encapsulates both data (attributes) and behaviors (methods). Understanding how to access and print the attributes of an object is fundamental for debugging, inspecting, and
2 min read
Searching a list of objects in Python
Searching for a single or group of objects can be done by iterating through a list. You might want to search a list of objects to find the object in the list of objects. It is very hard to look for objects manually, you can use the below-discussed method to search for objects in a list. You can also
3 min read
Sorting a CSV object by dates in Python
CSV stands for comma-separated values. A CSV file can be opened in Google Sheets or Excel and will be formatted as a spreadsheet. However, a CSV file is actually a plain-text file. It can also be opened with a text editor program such as Atom. In this article, we are going to see how to sort a CSV o
2 min read
Check if a List is Sorted or not - Python
We are given a list of numbers and our task is to check whether the list is sorted in increasing or decreasing order. For example, if the input is [1, 2, 3, 4], the output should be True, but for [3, 1, 2], it should be False.Using all()all() function checks if every pair of consecutive elements in
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
How to sort HTML elements by data-attribute ?
In this article let us see how we can sort HTML elements using data-attribute.We can sort the HTML elements like lists or any other using the data attribute. The data attribute consists of 2 parts which are the prefix and suffix, the prefix data- is compulsory and the suffix of data- can be any cust
3 min read
Creating a Sorted Merged List of Two Unsorted Lists in Python
Creating a sorted merged list of two unsorted lists involves combining the elements of both lists and sorting the resulting list in ascending order. For example: If we have list1 = [25, 18, 9] and list2 = [45, 3, 32] the output will be [3, 9, 18, 25, 32, 45].Using + OperatorThis method merges the tw
2 min read
Python - Get list of files in directory sorted by size
In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir(
3 min read