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 of tuple based on sum
Next article icon

Python - Sort list of list by specified index

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with a list of lists, we often need to sort the inner lists based on the values at a specific index. Sorting by a specified index is useful in the custom ordering of multidimensional data. In this article, we will explore different ways to sort a list of lists by a specified index in Python.

Using sorted()

The most simple and efficient way to sort a list of lists by a specified index is using the sorted() function with a key. It is efficient and concise for sorting by any index.

Python
a = [[1, 'Python', 50], [2, 'with', 30], [3, 'GFG', 40]]  # Sorting by the 2nd index  b = sorted(a, key=lambda x: x[2]) print(b) 

Output
[[2, 'with', 30], [3, 'GFG', 40], [1, 'Python', 50]] 

Explanation:

  • The sorted() function sorts the list of lists a based on the 3rd element (x[2]) of each sublist, as specified in the key argument using a lambda function.
  • The output is a new list where sublists are ordered by their price values (the 3rd element). The original list remains unchanged.

Let's explore some other methods to check how we can sort list of list by specified index.

Table of Content

  • Using itemgetter()
  • Using list.sort()
  • Sorting by Multiple Indices

Using itemgetter()

Using itemgetter() from the operator module is an efficient way to retrieve elements at specific indices in a list or other iterable.

Python
from operator import itemgetter  a = [[1, 'Python', 50], [2, 'is', 30], [3, 'fun!', 40]]  # Sorting by the 2nd index b = sorted(a, key=itemgetter(2)) print(b) 

Output
[[2, 'is', 30], [3, 'fun!', 40], [1, 'Python', 50]] 

Explanation:

  • itemgetter(2) fetches the value at the specified index.
  • This method is often more efficient than using a lambda function, especially with large datasets, as it avoids using lambda.

Using list.sort()

list.sort() method is used to sort a list in place, meaning it rearranges the elements of the list without creating a new list.

Python
a = [[1, 'Python', 50], [2, 'is', 30], [3, 'fun!', 40]]  # Sorting in place by the 2nd index a.sort(key=lambda x: x[2]) print(a) 

Output
[[2, 'is', 30], [3, 'fun!', 40], [1, 'Python', 50]] 

Explanation:

  • sort() method modifies the list data in place, arranging its sublists by the 3rd element (x[2]) as defined in the key argument using a lambda function.
  • Unlike sorted(), this does not create a new list but directly updates the original list, saving memory.

Sorting by Multiple Indices

Sometimes, we may want to sort a list by multiple indices in hierarchical order. It is useful for sorting data with ties at the first index.

Python
a = [[1, 'Python', 50], [2, 'is', 30], [3, 'fun!', 40]]  # Sorting by 2nd index first, then by 0th index sorted_data = sorted(a, key=lambda x: (x[1], x[0])) print(sorted_data) 

Output
[[1, 'Python', 50], [3, 'fun!', 40], [2, 'is', 30]] 

Explanation:

  • The key=lambda x: (x[1], x[0]) is a tuple that allows for multi-level sorting. Python compares tuples element by element, so it first sorts by the second element and resolves ties by the first element.

Next Article
Python | sort list of tuple based on sum
author
manjeet_04
Improve
Article Tags :
  • Sorting
  • Python
  • DSA
  • python-list
  • Python list-programs
Practice Tags :
  • python
  • python-list
  • Sorting

Similar Reads

  • Python - Returning index of a sorted list
    We are given a list we need to return the index of a element in a sorted list. For example, we are having a list li = [1, 2, 4, 5, 6] we need to find the index of element 4 so that it should return the index which is 2 in this case. Using bisect_left from bisect modulebisect_left() function from bis
    3 min read
  • Python - Get list of files in directory sorted by size
    In this article, we will be looking at the different approaches to get the list of the files in the given directory in the sorted order of size in the Python programming language. The two different approaches to get the list of files in a directory are sorted by size is as follows: Using os.listdir(
    3 min read
  • Python | sort list of tuple based on sum
    Given, a list of tuple, the task is to sort the list of tuples based on the sum of elements in the tuple. Examples: Input: [(4, 5), (2, 3), (6, 7), (2, 8)] Output: [(2, 3), (4, 5), (2, 8), (6, 7)] Input: [(3, 4), (7, 8), (6, 5)] Output: [(3, 4), (6, 5), (7, 8)] # Method 1: Using bubble sort Using th
    4 min read
  • Check if a List is Sorted or not - Python
    We are given a list of numbers and our task is to check whether the list is sorted in increasing or decreasing order. For example, if the input is [1, 2, 3, 4], the output should be True, but for [3, 1, 2], it should be False. Using all()all() function checks if every pair of consecutive elements in
    3 min read
  • Creating a Sorted Merged List of Two Unsorted Lists in Python
    Creating a sorted merged list of two unsorted lists involves combining the elements of both lists and sorting the resulting list in ascending order. For example: If we have list1 = [25, 18, 9] and list2 = [45, 3, 32] the output will be [3, 9, 18, 25, 32, 45]. Using + OperatorThis method merges the t
    2 min read
  • Internal working of list in Python
    Introduction to Python lists : Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becom
    3 min read
  • Python List index() - Find Index of Item
    index() method in Python is a helpful tool when you want to find the position of a specific item in a list. It works by searching through the list from the beginning and returning the index (position) of the first occurrence of the element you're looking for. Example: [GFGTABS] Python a = ["cat
    3 min read
  • Python | Sort a tuple by its float element
    In this article, we will see how we can sort a tuple (consisting of float elements) using its float elements. Here we will see how to do this by using the built-in method sorted() and how can this be done using in place method of sorting. Examples: Input : tuple = [('lucky', '18.265'), ('nikhil', '1
    3 min read
  • Sort a list of objects by multiple attributes in Python
    In this article, we are going to learn how to sort a list by multiple attributes with Python. Introduction Python is a dynamically typed language that offers numerous data types, such as list, tuple, set, dictionary, etc. and sorting is the most commonly used operation on any data structures such as
    7 min read
  • Sort a List According to the Length of the Elements - Python
    We are given a list of strings and our task is to sort the list based on the length of each string. For example, if the input is ["Python", "C", "Java", "JavaScript", "Go"], the output should be ["C", "Go", "Java", "Python", "JavaScript"] since shorter strings come first. Using sorted() sorted() fun
    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