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 explain the solution and provide ready-to-use examples so that you can easily consume the code in your programs.
How to Sort List of Lists in Python
Let’s explore different methods with simple explanations and practical examples. Mainly three methods are most common for sorting a list 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.
Main Problem Statement
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]
]
Simple Ways to Sort a List of Lists
Now, go through the below techniques, and first read them carefully. After that, you can try running the code in your Python IDE.
Using Sorted() Method
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() to create 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 sorts the student’s nested list and prints 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 produce a similar result. So, we won’t be repeating the output for the remaining methods.
Using List Comprehension
Another method that we can use is Python list comprehension. It is a one-line expression 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())
Using Lambda Expression
This is the final technique for our job. It uses 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 go through the steps to get 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())
Hopefully, you have enjoyed using the above techniques to solve the sorting problem. However, the tutorial is not over yet. Let’s take a more difficult challenge and apply the methods we learned.
Practice Problem: Sort a List of Employees
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. Please go through the example given below.
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 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 sets 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']
Must Read:
1. Python Nested Lists
2. Python Add Lists
3. Python Add List Elements
4. Sort Python Lists Alphabetically
5. Python Sort List of Strings
6. Python Sort a Dictionary
7. Python Find List Shape
8. Python Compare Two Lists
9. Python Sets vs. Lists
10. Python Map() vs List Comprehension
11. Python Generators vs. List Comprehensions
12. Python Sort List in Descending Order
13. Python Sort List of Numbers or Integers
Before You Leave
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 will help you become better at coding. It also enables you to solve problems involving nested data structures more effectively.
Lastly, our site needs your support to remain free. Share this post on social media (Facebook/Twitter) if you gained some knowledge from this tutorial.
Happy coding,
TechBeamers.