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 | Split list of strings into sublists based on length
Next article icon

Python – Sort list of lists by the size of sublists

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

The problem is to sort a list of lists based on the size of each sublist. For example, given the list [[1, 2], [1], [1, 2, 3]], the sorted result should be [[1], [1, 2], [1, 2, 3]] when sorted in ascending order. We will explore multiple methods to do this in Python.

Using sorted() with len()

This method uses Python’s built-in sorted() function, which allows us to specify a custom key for sorting. Here, we use the length of each sublist as the key.

Python
# Input list of lists a = [[1, 2], [1], [1, 2, 3]]  # Sort based on sublist size result = sorted(a, key=len) print(result)   

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

Explanation:

  • sorted() function sorts the list based on a key.
  • We specify len as the key, which calculates the size of each sublist.

Let’s explore some more ways and see how we can sort list of lists by the size of sublists.

Table of Content

  • Using sort() Method with len as Key
  • Using List Comprehension and sorted()
  • Using For Loop

Using sort() with len()

If we want to sort the list in place without creating a new list, we can use the sort() method.

Python
# Input list of lists a = [[1, 2], [3, 4, 5], [6]]  # Sort the list in place by the size of the sublists a.sort(key=len) print(a)   

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

Explanation:

  • sort() method modifies the original list.
  • It uses the same approach as the sorted() function but works directly on the list.
  • This method is slightly more memory-efficient because it avoids creating a new list.

Using List Comprehension and sorted()

We can use a combination of list comprehension and sorted() to sort the list and explicitly display the sizes of the sublists for better understanding.

Python
# Input list of lists a = [[1, 2], [3, 4, 5], [6]]  # Sort the list in place by the size of the sublists a.sort(key=len) print(a)  

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

Explanation:

  • This method is a variation of the first one but explicitly uses list comprehension to emphasize the sublist selection process.
  • It’s useful for demonstrating the logic but doesn’t differ significantly in efficiency.

Using For Loop

This is a more manual approach which involves iterating through the list and sorting it manually using a simple for loop.

Python
# Input list of lists a = [[1, 2], [3, 4, 5], [6]]  # Sort the list manually using a nested loop for i in range(len(a)):     for j in range(len(a) - i - 1):         if len(a[j]) > len(a[j + 1]):             a[j], a[j + 1] = a[j + 1], a[j] print(a)  

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

Explanation: This method uses a bubble sort algorithm, comparing adjacent sublists and swapping them based on their size.



Next Article
Python | Split list of strings into sublists based on length
author
garg_ak0109
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • python-list
  • Python-list-of-lists
  • Python-sort
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python - Sort list of numbers by sum of their digits
    Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case. Using sorted() with a Lambda Functionsorted() function
    2 min read
  • Sort a List of Tuples by Second Item - Python
    The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)],
    2 min read
  • Sort Tuple of Lists in Python
    The task of sorting a tuple of lists involves iterating through each list inside the tuple and sorting its elements. Since tuples are immutable, we cannot modify them directly, so we must create a new tuple containing the sorted lists. For example, given a tuple of lists a = ([2, 1, 5], [1, 5, 7], [
    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 | Split list of strings into sublists based on length
    Given a list of strings, write a Python program to split the list into sublists based on string length. Examples: Input : ['The', 'art', 'of', 'programming'] Output : [['of'], ['The', 'art'], ['programming']] Input : ['Welcome', 'to', 'geeksforgeeks'] Output : [['to'], ['Welcome'], ['geeksforgeeks']
    3 min read
  • Find the size of a list - Python
    In Python, a list is a collection data type that can store elements in an ordered manner and can also have duplicate elements. The size of a list means the amount of memory (in bytes) occupied by a list object. In this article, we will learn various ways to get the size of a python list. 1.Using get
    2 min read
  • Python | Sort given list of strings by part of string
    We are given with a list of strings, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string. Using sort() with lambda functionThis
    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 - Sort by Units Digit in List
    Given a Integer list, sort by unit digits. Input : test_list = [76, 434, 23, 22342] Output : [22342, 23, 434, 76] Explanation : 2 < 3 < 4 < 6, sorted by unit digits. Input : test_list = [76, 4349, 23, 22342] Output : [22342, 23, 76, 4349] Explanation : 2 < 3 < 6 < 9, sorted by unit
    7 min read
  • Python - Reverse Row sort in Lists of List
    We are given a list of lists where each inner list represents a row and our task is to sort each row in descending order while keeping the overall structure intact. For example, given a = [[5, 2, 8], [9, 1, 4], [6, 7, 3]], after sorting each row in reverse order, the result will be [[8, 5, 2], [9, 4
    3 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