Home  >  Article  >  Backend Development  >  Why doesn't list.sort() return a sorted list in Python?

Why doesn't list.sort() return a sorted list in Python?

王林
王林forward
2023-09-18 09:29:061153browse

Why doesnt list.sort() return a sorted list in Python?

Example

In this example, we first look at the usage of list.sort() before continuing. Here we create a list and sort it in ascending order using 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']

In cases where performance is more important, copying a list just for sorting is not considered good and is wasteful. Therefore, list.sort() sorts the list in-place. This method does not return a sorted list. This way you won't be tricked into accidentally overwriting the list when you need a sorted copy but also need to keep the unsorted version.

Use the built-in sorted() function to return a new list. This function creates a new list based on the provided iterable, sorts it and returns it.

Use sorted() to sort a dictionary list based on value

Example

We have now used the sorted() method to sort the dictionary list.

# 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}])

The above is the detailed content of Why doesn't list.sort() return a sorted list in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete