w3resource

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


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

Sample Solution:

Python Code :

# Define a function 'index_on_inner_list' that sorts a list of lists based on a specified index of inner lists
def index_on_inner_list(list_data, index_no):
    # Sort the 'list_data' based on the specified 'index_no' of inner lists using the 'sorted' function
    # The 'key' parameter uses a lambda function to access the element at the given 'index_no'
    result = sorted(list_data, key=lambda x: x[index_no])
    
    # Return the sorted list of lists
    return result

# Create a list of tuples 'students' containing names and two additional elements for each student
students = [
    ('Greyson Fulton', 98, 99),
    ('Brady Kent', 97, 96),
    ('Wyatt Knott', 91, 94),
    ('Beau Turnbull', 94, 98)
]

# Print the original list of tuples 'students'
print("Original list:")
print(students)

# Sort the list of tuples based on the index 0 of the inner lists and print the result
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))

# Sort the list of tuples based on the index 2 of the inner lists and print the result
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)]

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 Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.