Sort List of Lists

Tags: Function, List

Write a Python function named sort_list_of_lists that sorts a list of lists based on the second element in each list. Return the sorted list.

Example 1:

Input: sort_list_of_lists([[1, 2], [3, 1], [2, 3]]) 

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

Example 2:

Input: sort_list_of_lists([['a', 'b'], ['c', 'a'], ['b', 'c']]) 

Output: [['c', 'a'], ['a', 'b'], ['b', 'c']]

Use the sort() function with the key parameter.

def sort_list_of_lists(lst):
    return sorted(lst, key=lambda x: x[1])

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!