Sort list of lists by index of inner Python list

In this article, we are going to learn how to Sort list of lists by index of inner Python list. We will use the nested lists and then we will sort the lists based on the indexes in the nested list. The user will be able to give input on which index he wants to sort on. We will make use of the below python functions. We will write code by using both functions in a different logic.


sorted(iterable, key, reverse)

Parameters: sorted takes three parameters of which two are optional.

  • Iterable: sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
  • Key(optional): A function that would serve as a key or a basis of sort comparison.
  • Reverse(optional): If True, then the iterable would be sorted in reverse (descending) order, by default it is set as False.
  • Return: Returns a list with elements in sorted order.

Python sort() Function syntax:-

list.sort(reverse=True|False, key=myFunc)

Parameter Description

  • reverses Optional. reverse=True will sort the list descending. Default is reverse=False
  • key Optional. A function to specify the sorting criteria(s)

1. Sort list of lists by index of inner Python list

  • First, create a List of lists.
  • Now enter the index through what you want to sort in a list of lists.
  • In the method1 I use the sorted and lambda function
  • In the lambda function, we pass the index of the inner list by which sorting is done.
  • The sorted function returns a list so we can store it in a variable- called new_list and then print it.
  • In method 2 I use another inbuilt method for sorting called sort () which is only used for lists.
  • In the sort method, I pass the lambda function and index for sorting the inner list.
  • The sort method updates the current list so no need to create a new list.
OrgList=[['Rahul', 56, 118],['Vidhi', 32, 120],['Nanoha', 71, 67],['Akkira', 13, 81]]

Index=int(input("Enter Index(0-2): "))
if Index==0:
    print("Sorting Performing By Index 0")
elif Index==1:
    print("Sorting Performing By Index 1.")
    print("Sorting Performing By Index 2")
print("Method 1")
sorted_list = sorted(OrgList,key=lambda x:x[Index])

print("Method 2")
OrgList.sort(key=lambda x:x[Index])


Enter Index(0-2): 1
Sorting Performing By Index 1.
Method 1
[[‘Akkira’, 13, 81], [‘Vidhi’, 32, 120], [‘Rahul’, 56, 118], [‘Nanoha’, 71, 67]]
Method 2
[[‘Akkira’, 13, 81], [‘Vidhi’, 32, 120], [‘Rahul’, 56, 118], [‘Nanoha’, 71, 67]]