Sorting lists of lists in Python presents a challenge when you need to organize structured data with multiple levels. Python’s built-in sorting methods don’t directly handle this complexity. To achieve the desired sorting, you need to leverage specific techniques. We’ll be detailing the solution and provide ready-to-use methods that you can directly consume in your projects.
How to Sort List of Lists in Python
Let’s explore different methods with simple explanations and practical examples. There are mainly three main methods we can use to sort lists of lists in Python. However, before we jump on to the techniques, let’s define a problem scenario. We’ll then be using each method to solve this.
Problem Scenario: Sorting a List of Students Based on Exam Scores
Consider a list of students where each sublist represents [name, age, exam_score]
. We want to sort the students based on their exam scores in ascending order.
students = [
["Meenakshi", 32, 95],
["Soumya", 20, 88],
["Manya", 21, 75],
["Rahul", 23, 92],
["Rohit", 22, 95]
]
Now, go through the below techniques, and first read them carefully. After that, you can try running the code in your Python IDE.
1. Using sorted() with a Key Function
The first solution is by using the Python sorted() function. While using it, we need to follow the below steps.
- Define a key function that extracts the sorting element from each sublist.
- Pass this function to sorted(), which creates a new sorted list.
- Preserves original order for equal elements (stable).
def print_info(data):
print("Original List of Students:")
for student in data:
print(student)
print()
# Method 1: Using sorted() with a Key Function
def sort_by_sorted(data):
print("Method 1: Using sorted() with a Key Function")
print("Before Sorting:")
print_info(data) # Fix: Correct function name
sorted_students = sorted(data, key=lambda x: x[2])
print("After Sorting:")
for student in sorted_students:
print(student)
print()
students = [
["Meenakshi", 32, 95],
["Soumya", 20, 88],
["Manya", 21, 75],
["Rahul", 23, 92],
["Rohit", 22, 95]
]
# Demonstrate sorting by sorted() method
sort_by_sorted(students.copy())
When you run the above code, it will sort the student’s nested list and print the following result.
Before Sorting:
Original List of Students:
['Meenakshi', 32, 95]
['Soumya', 20, 88]
['Manya', 21, 75]
['Rahul', 23, 92]
['Rohit', 22, 95]
After Sorting:
['Manya', 21, 75]
['Soumya', 20, 88]
['Rahul', 23, 92]
['Meenakshi', 32, 95]
['Rohit', 22, 95]
Please note – that the code in each technique would solve the same problem, and hence produce a similar result. So, we won’t be repeating the output for the remaining methods.
2. Using List Comprehension
Another method that we can use is Python list comprehension. It is a one-line expression that we mainly use to filter a list in Python. Let’s now see the steps we need to take to achieve our goal.
- Create a new sorted list using list comprehension.
- Concise for simple sorting criteria.
- Doesn’t always preserve the original order for equal elements.
def print_info(data):
print("Original List of Students:")
for student in data:
print(student)
print()
# Method 2: Using List Comprehension
def sort_by_lc(data):
print("Method 2: Using List Comprehension")
print("Before Sorting:")
print_info(data) # Fix: Correct function name
sorted_students_lc = [student for student in sorted(data, key=lambda x: x[2])]
print("After Sorting:")
for student in sorted_students_lc:
print(student)
print()
students = [
["Meenakshi", 32, 95],
["Soumya", 20, 88],
["Manya", 21, 75],
["Rahul", 23, 92],
["Rohit", 22, 95]
]
# Demonstrate sorting by List Compr. method
sort_by_lc(students.copy())
3. Using lambda with sort() to Sort List of Lists
The final technique that can do our job is the combination of Python lambda and the sort() function. Lambda is a special keyword in Python that can help us create inline functions. Sometimes such functions are quite simple and useful. Let’s see what steps we need to take for this method to work.
- Define a lambda function directly within the
sort()
method. - Modifies the original list in place.
- Doesn’t always preserve the original order for equal elements.
def print_info(data):
print("Original List of Students:")
for student in data:
print(student)
print()
# Method 3: Using lambda with sort()
def sort_by_lambda(data):
print("Method 3: Using lambda with sort()")
print("Before Sorting:")
print_info(data) # Fix: Correct function name
data.sort(key=lambda x: x[2])
print("After Sorting:")
for student in data:
print(student)
print()
students = [
["Meenakshi", 32, 95],
["Soumya", 20, 88],
["Manya", 21, 75],
["Rahul", 23, 92],
["Rohit", 22, 95]
]
# Demonstrate sorting by lambda method
sort_by_lambda(students.copy())
Hope, you would have enjoyed understanding and solving the above techniques and solutions. However, the tutorial is not over yet. Let’s take another one but a little more complex problem and apply the methods we learned.
Complex Problem Scenario: Sorting a List of Employees Based on Multiple Criteria
Consider a list of employee records where each sublist represents [name, age, salary, dept]
. The task is to sort the employees based on the department in ascending order, and within each department, sort them based on age in descending order.
employees = [
["Meenakshi", 28, 60000, "HR"],
["Soumya", 22, 55000, "IT"],
["Manya", 25, 65000, "Sales"],
["Ahann", 30, 70000, "IT"],
["Vihan", 28, 62000, "Sales"],
["Rishan", 35, 75000, "HR"]
]
Method 1: By Using sorted()
Problem Solution:
Define a key function to extract the department and age (x[3], -x[1]
) from each sublist. Pass this function to sorted() to create a new sorted list. Review the below function that we created.
Code:
def sort_by_sorted(data):
print("Method 1: Using sorted() with a Key Function")
print("Before Sorting:")
print_info(data)
sorted_empls = sorted(data, key=lambda x: (x[3], -x[1]))
print("After Sorting:")
for empl in sorted_empls:
print(empl)
print()
Method 2: By Using List Comprehension
Problem Solution:
Create a new sorted list using list comprehension with a concise expression for sorting based on department and age. Check up on the following Python function we wrote to do the task.
def sort_by_lc(data):
print("Method 2: Using List Comprehension")
print("Before Sorting:")
print_info(data)
sorted_empls = [empl for empl in sorted(data, key=lambda x: (x[3], -x[1]))]
print("After Sorting:")
for empl in sorted_empls:
print(empl)
print()
Method 3: By Using lambda
with sort()
Problem Solution:
Define a lambda function directly within the sort()
method, sorting the original list in place based on department and age. We have created the following custom function to do the task.
def sort_by_lambda(data):
print("Method 3: Using lambda with sort()")
print("Before Sorting:")
print_info(data)
data.sort(key=lambda x: (x[3], -x[1]))
print("After Sorting:")
for empl in data:
print(empl)
print()
Note:
- In each method, the key function is designed to sort first by department in ascending order and then by age in descending order within each department.
Now, let’s define the print_info
function and demonstrate each sorting method:
def print_info(data):
print("Original List of Employees:")
for empl in data:
print(empl)
print()
# Demonstrate each sorting method
sort_by_sorted(employees.copy())
sort_by_lc(employees.copy())
sort_by_lambda(employees.copy())
Now, it’s time that you club all the pieces of code together and run in your Python IDE. We have tested it at our end, it gives the following output. The results will have three such sets of the output but we are showing here only one.
Before Sorting:
Original List of Employees:
['Meenakshi', 28, 60000, 'HR']
['Soumya', 22, 55000, 'IT']
['Manya', 25, 65000, 'Sales']
['Ahann', 30, 70000, 'IT']
['Vihan', 28, 62000, 'Sales']
['Rishan', 35, 75000, 'HR']
After Sorting:
['Rishan', 35, 75000, 'HR']
['Meenakshi', 28, 60000, 'HR']
['Ahann', 30, 70000, 'IT']
['Soumya', 22, 55000, 'IT']
['Vihan', 28, 62000, 'Sales']
['Manya', 25, 65000, 'Sales']
Conclusion
In conclusion, sorting lists of lists in Python means making choices between creating new lists or changing the existing ones. It’s also important to think about stability in sorting. Knowing these methods helps you become a better programmer. It also enables you to solve problems involving nested data structures more effectively.
Happy Coding,
Team TechBeamers