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

王林
Release: 2023-09-18 09:29:06
forward
1193 people have browsed it

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)
Copy after login

Output

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

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']))
Copy after login

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}])
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!