TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Sorting List of Lists in Python Explained With Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
HowToPython BasicPython Tutorials

Sorting List of Lists in Python Explained With Examples

Last updated: Feb 04, 2024 5:02 pm
By Meenakshi Agarwal
Share
10 Min Read
Sort List of Lists in Python Explained With Examples
SHARE

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.

Contents
1. Using sorted() with a Key Function2. Using List Comprehension3. Using lambda with sort() to Sort List of ListsComplex Problem Scenario: Sorting a List of Employees Based on Multiple CriteriaMethod 1: By Using sorted()Method 2: By Using List ComprehensionMethod 3: By Using lambda with sort()

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

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Pandas Add Row Using Multiple Methods in Python Pandas Add Row Using Multiple Methods
Next Article Linux Commands for Beginners With Examples Basic Linux Commands for Beginners With Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x