How to Sort a Nested List in Python by the Second List Item?

Estimated read time 2 min read

To sort a nested list in Python by the second list item, you can pass a lambda function as the key argument to the sorted() function that extracts the second item from each sublist. Here is an example code that sorts a nested list by the second list item:

# Create a sample nested list
my_list = [['John', 25, 'male'], ['Alice', 20, 'female'], ['Bob', 30, 'male'], ['Charlie', 22, 'male']]

# Sort the nested list by the second item of each sublist
sorted_list = sorted(my_list, key=lambda x: x[1])

# Print the sorted list
print(sorted_list)

In this code, we first create a sample nested list my_list consisting of four sublists, each containing three elements.

We then use the sorted() function to sort the nested list by the second item of each sublist. We pass a lambda function key=lambda x: x[1] to the sorted() function that returns the second element x[1] of each sublist x in the list of sublists. The sorted() function returns a new sorted list of sublists, where each sublist is sorted by the second item. We assign this new list to the variable sorted_list.

We then print the sorted list using the print() function. The output of this code is [['Alice', 20, 'female'], ['Charlie', 22, 'male'], ['John', 25, 'male'], ['Bob', 30, 'male']], where the sublists are sorted by the second item.

Note that the sorted() function returns a new sorted list, and does not modify the original list. If you want to modify the original list in place, you can use the sort() method of the list instead of the sorted() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply