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:
Sort a List of Dictionaries by a Value of the Dictionary - Python
Next article icon

Sort List of Lists by Lexicographic Value and then Length – Python

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

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 would yield [[1, 2], [3, 2], [1, 4, 6], [3, 2, 1]].

Using sort() Twice 

This method first sorts the lists lexicographically and then by length. sort() function is called twice: the first to handle lexicographic sorting and the second to sort by the list length.

Python
li = [[3, 2], [1, 4, 6], [1, 2], [3, 2, 1]]  li.sort()  # lexicographic sort li.sort(key=len) # length-based sort  print(li)  

Output
[[1, 2], [3, 2], [1, 4, 6], [3, 2, 1]] 

Using Lambda Function

This method optimizes the sorting process by calling the sorted() function only once then lambda function is used as the key combining the sorting criteria of length and lexicographic order in a single step.

Python
li = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]  # sorting using lambda function res = sorted(li, key=lambda x: (len(x), x))  print(res)   

Output
[[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]] 

Explanation: The key in sorted() uses a lambda function that generates a tuple (len(x), x) for each sublist x. This ensures sorting by length first and then lexicographically if lengths are the same.

Using cmp_to_key from functools

Instead of sorting directly with a key function we use cmp_to_key() to define a custom sorting behavior that sorts lists first by length and then lexicographically.

Python
from functools import cmp_to_key  li = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]  # Sorting using cmp_to_key, first by length, then lexicographically res = sorted(li, key=cmp_to_key(lambda a, b: (len(a) - len(b)) or (-1 if a < b else (1 if a > b else 0))))  print(res) 

Output
[[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]] 

Explanation:

  • lambda function works by first comparing the lengths of a and b and if they are different it sorts based on length.
  • If the lengths are equal then it compares the lists lexicographically using these notations: -1 (less than), 1 (greater than), or 0 (equal).

Using Heap Sort

This method uses heap data structure to sort the list of lists in which we first convert the lists into a heap and then extract the minimum element one by one, ensuring they are sorted by length and lexicographically.

Python
import heapq  li = [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]  # Convert the list into a heap and sort heapq.heapify(li) res = [heapq.heappop(li) for _ in range(len(li))]  print(res) 

Output
[[1, 4, 3, 2], [1, 4, 6, 7], [5, 4, 1]] 

Explanation

  • heapq.heapify() transforms the list into a heap ensuring it can be accessed in a sorted order.
  • heappop() retrieves the smallest elements based on the sorting rules which ensures the correct order.


Next Article
Sort a List of Dictionaries by a Value of the Dictionary - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • python-list
  • Python-list-of-lists
  • Python-sort
Practice Tags :
  • python
  • python-list

Similar Reads

  • Sort List of Lists Ascending and then Descending in Python
    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 keysorted() function is a flexible and efficient way to sort lists. It creates a new list while leaving the original unchanged. [GFGTABS] Python a = [[1,
    3 min read
  • Sort a List of Python Dictionaries by a Value
    Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
    3 min read
  • Sort a List of Dictionaries by a Value of the Dictionary - Python
    We are given a list of dictionaries where each dictionary contains multiple key-value pairs and our task is to sort this list based on the value of a specific key. For example, Given the list: students = [{'name': 'David', 'score': 85}, {'name': 'Sophia', 'score': 92}, {'name': 'Ethan', 'score': 78}
    2 min read
  • Convert List of Tuples to Dictionary Value Lists - Python
    The task is to convert a list of tuples into a dictionary where the first element of each tuple serves as the key and the second element becomes the value. If a key appears multiple times in the list, its values should be grouped together in a list. For example, given the list li = [(1, 'gfg'), (1,
    4 min read
  • Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple - Python
    The task of sorting a list of tuples in Python based on the last element of each tuple is a common task when working with structured data. This involves arranging the tuples in increasing order according to their second or last value, often for easier data analysis or searching. For example, given a
    3 min read
  • Sort the values of first list using second list in Python
    Sorting the values of the first list using the second list in Python is commonly needed in applications involving data alignment or dependency sorting. In this article, we will explore different methods to Sort the values of the first list using the second list in Python. Using zip() and sorted() zi
    3 min read
  • Python - Sort Tuple List by Nth Element of Tuple
    We are given list of tuple we need to sort tuple by Nth element of each tuple. For example d = [(1, 5), (3, 2), (2, 8), (4, 1)] and k=1 we need to sort by 1st element of each tuple so that output for given list should be [(4, 1), (3, 2), (1, 5), (2, 8)] Using sorted() with lambdasorted() function wi
    3 min read
  • Python | Sort dictionary by value list length
    While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda
    4 min read
  • Ways to Sort List of Float Values - Python
    Given a list of float values, our task is to sort them in ascending order. For example, given [3.1, 2.4, 5.6, 1.8], the sorted output should be: [1.8, 2.4, 3.1, 5.6] Using sorted()Python’s built-in sorted() function sorts the list in ascending order by default. It is efficient and works well for mos
    2 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