Why doesn’t list.sort() return the sorted list in Python?


Example

In this example, let’s first see the usage of list.sort() before moving further. Here, we have created a List and sorted in Ascending order using the sort() method −

# Creating a List myList = ["Jacob", "Harry", "Mark", "Anthony"] # Displaying the List print("List = ",myList) # Sort the Lists in Ascending Order myList.sort() # Display the sorted List print("Sort (Ascending Order) = ",myList)

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Sort (Ascending Order) =  ['Anthony', 'Harry', 'Jacob', 'Mark']

Where performance matters more, making a copy of the list just to sort it wouldn’t be considered good and is wasteful. Therefore, list.sort() sorts the list in place. This method does not return the sorted list. This way, you won’t be fooled into accidentally overwriting a list when you need a sorted copy but also need to keep the unsorted version around.

Return a new list using the built-in sorted() function instead. This function creates a new list from a provided iterable, sorts it and returns it.

Using sorted() to Sort a List of Dictionaries using values

Example

We have now used the sorted() method to sort a list of dictionaries.

# List of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the lambda function print("Sorted = \n",sorted(d, key = lambda item: item['marks']))

Output

('Dictionary = \n', [{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}])
('Sorted = \n', [{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}])

Updated on: 20-Sep-2022

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements