w3resource

Python: Sort a list of lists by a given index of the inner list using lambda

Python Lambda: Exercise-37 with Solution

Write a Python program to sort a list of lists by a given index of the inner list using lambda.

Sample Solution:

Python Code :

def index_on_inner_list(list_data, index_no):
    result = sorted(list_data, key=lambda x: x[index_no])
    return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] 
print ("Original list:")
print(students)
index_no = 0
print("\nSort the said list of lists by a given index","( Index =",index_no,") of the inner list")
print(index_on_inner_list(students, index_no))
index_no = 2
print("\nSort the said list of lists by a given index","( Index =",index_no,") of the inner list")
print(index_on_inner_list(students, index_no))

Sample Output:

Original list:
[('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]

Sort the said list of lists by a given index ( Index =  0 ) of the inner list
[('Beau Turnbull', 94, 98), ('Brady Kent', 97, 96), ('Greyson Fulton', 98, 99), ('Wyatt Knott', 91, 94)]

Sort the said list of lists by a given index ( Index =  2 ) of the inner list
[('Wyatt Knott', 91, 94), ('Brady Kent', 97, 96), ('Beau Turnbull', 94, 98), ('Greyson Fulton', 98, 99)]

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to extract the nth element from a given list of tuples using lambda.
Next: Write a Python program to remove all elements from a given list present in another list using lambda.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Given a predicate function, fn, and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate:

Example:

def tips_check_prop(fn, prop):
  return lambda obj: fn(obj[prop])
check_age = tips_check_prop(lambda x: x >= 25, 'age')
user = {'name': 'Owen', 'age': 25}

print(check_age(user))

Output:

True