Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Sort List items on basis of their Digits
Next article icon

Sort List of Lists Ascending and then Descending in Python

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting a list of lists in Python can be done in many ways, we will explore the methods to achieve the same in this article.

Using sorted() with a key

sorted() function is a flexible and efficient way to sort lists. It creates a new list while leaving the original unchanged.

Python
a = [[1, 2, 3], [3, 2, 1], [2, 3, 1]]  # Sort in ascending order based on the first element asc = sorted(a, key=lambda x: x[0]) print(asc)     # Sort in descending order based on the first element desc = sorted(a, key=lambda x: x[0], reverse=True) print(desc)   

Output
[[1, 2, 3], [2, 3, 1], [3, 2, 1]] [[3, 2, 1], [2, 3, 1], [1, 2, 3]] 

Explanation:

  • Key parameter is used to specify the sorting criterion (in this case, the first element).
  • Reverse parameter is used for descending order sorting.

Let's explore some more methods and see how we can sort list of lists in ascending then descending order in Python.

Table of Content

  • Using sort() method
  • Using itemgetter() from operator module
  • Using a custom comparator

Using sort() method

sort() method sorts the list in place, making it memory efficient when a new list is unnecessary.

Python
a = [[1, 2, 3], [3, 2, 1], [2, 3, 1]]  # Sort in ascending order based on the first element a.sort(key=lambda x: x[0]) print(a)   # Sort in descending order based on the first element a.sort(key=lambda x: x[0], reverse=True) print(a)   

Output
[[1, 2, 3], [2, 3, 1], [3, 2, 1]] [[3, 2, 1], [2, 3, 1], [1, 2, 3]] 

Explanation: This method modifies the original list, saving memory as no new list is created.

Using itemgetter() from operator module

itemgetter() function from the operator module is another efficient way to sort lists, especially for readability.

Python
from operator import itemgetter  a = [[1, 2, 3], [3, 2, 1], [2, 3, 1]]  # Sort in ascending order based on the first element asc = sorted(a, key=itemgetter(0)) print(asc)  # Sort in descending order based on the first element desc = sorted(a, key=itemgetter(0), reverse=True) print(desc)  

Output
[[1, 2, 3], [2, 3, 1], [3, 2, 1]] [[3, 2, 1], [2, 3, 1], [1, 2, 3]] 

Explanation: itemgetter() function simplifies accessing specific indices in the list, making the code more readable.

Using a custom comparator

We can use a custom comparator with the functools.cmp_to_key() function to define complex sorting behavior.

Python
from functools import cmp_to_key a = [[1, 2, 3], [3, 2, 1], [2, 3, 1]]  # Custom comparator function def compare(x, y):     return x[0] - y[0]  # Sort in ascending order based on the first element asc = sorted(a, key=cmp_to_key(compare)) print(asc)  

Output
[[1, 2, 3], [2, 3, 1], [3, 2, 1]] 

Explanation: Custom comparator function allows for more complex sorting criteria but is generally slower than using a key.


Next Article
Python - Sort List items on basis of their Digits

G

gfgintzqnk
Improve
Article Tags :
  • Python
  • Python Programs
  • python-list
  • python sorting-exercises
Practice Tags :
  • python
  • python-list

Similar Reads

  • Sort List of Lists by Lexicographic Value and then Length - Python
    In this problem, sorting a list of lists by lexicographic value and then length means arranging the sublists first by their natural order (lexicographically) and then by their size. For example: For the list [[3, 2], [1, 4, 6], [1, 2], [3, 2, 1]], sorting by lexicographic value and then by length wo
    3 min read
  • Sorting List of Dictionaries in Descending Order in Python
    The task of sorting a list of dictionaries in descending order involves organizing the dictionaries based on a specific key in reverse order. For example, given a list of dictionaries like a = [{'class': '5', 'section': 3}, {'Class': 'Five', 'section': 7}, {'Class': 'Five', 'section': 2}], the goal
    3 min read
  • Python - Sort List items on basis of their Digits
    Given List of elements, perform sorting on basis of digits of numbers. Input : test_list = [434, 211, 12, 3] Output : [12, 211, 3, 434] Explanation : 3 < 12, still later in list, as initial digit, 1 < 3. Hence sorted by digits rather than number. Input : test_list = [534, 211, 12, 7] Output :
    2 min read
  • Python | Check for Descending Sorted List
    The sorted operation of list is essential operation in many application. But it takes best of O(nlogn) time complexity, hence one hopes to avoid this. So, to check if this is required or not, knowing if list is by default reverse sorted or not, one can check if list is sorted or not. Lets discuss va
    3 min read
  • Python Program For Sorting A Linked List That Is Sorted Alternating Ascending And Descending Orders
    Given a Linked List. The Linked List is in alternating ascending and descending orders. Sort the list efficiently.  Example:  Input List: 10 -> 40 -> 53 -> 30 -> 67 -> 12 -> 89 -> NULL Output List: 10 -> 12 -> 30 -> 40 -> 53 -> 67 -> 89 -> NULL Input List: 1 -> 4 -> 3 -> 2 -> 5 -> NULL Output List:
    4 min read
  • Convert List of String into Sorted List of Integer - Python
    We are given a list of string a = ['3', '1', '4', '1', '5'] we need to convert all the given string data inside the list into int and sort them into ascending order so the output list becomes a = [1, 1, 3, 4, 5]. This can be achieved by first converting each string to an integer and then sorting the
    3 min read
  • Python | Sort list of dates given as strings
    To sort a list of dates given as strings in Python, we can convert the date strings to datetime objects for accurate comparison. Once converted, the list can be sorted using Python's built-in sorted() or list.sort() functions. This ensures the dates are sorted chronologically. Using pandas.to_dateti
    3 min read
  • Python - Sort list according to other list order
    Sorting a list based on the order defined by another list is a common requirement in Python, especially in scenarios involving custom sorting logic. This ensures that elements in the first list appear in the exact order specified in the second list. Python provides various methods to accomplish this
    2 min read
  • Sorting List of Lists with First Element of Each Sub-List in Python
    In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you're dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list o
    3 min read
  • Python | Sorting list of lists with similar list elements
    Sorting has always been a key operation that is performed for many applications and also as a subproblem to many problems. Many variations and techniques have been discussed and their knowledge can be useful to have while programming. This article discusses the sorting of lists containing a list. Le
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences