Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why doesn't list.sort() return the sorted list in Python?
The list.sort() method in Python sorts a list in-place and returns None instead of the sorted list. This design choice prevents accidental overwriting of the original list and improves memory efficiency.
Why list.sort() Returns None
Python's list.sort() modifies the original list directly rather than creating a new one. This in-place operation is more memory-efficient and follows Python's principle that methods performing in-place modifications should return None.
Example: Using list.sort()
Here's how list.sort() works in practice ?
# Creating a List
names = ["Jacob", "Harry", "Mark", "Anthony"]
# Displaying the original List
print("Original List =", names)
# Sort the List in Ascending Order (returns None)
result = names.sort()
print("Return value of sort():", result)
# Display the sorted List
print("Sorted List =", names)
Original List = ['Jacob', 'Harry', 'Mark', 'Anthony'] Return value of sort(): None Sorted List = ['Anthony', 'Harry', 'Jacob', 'Mark']
Alternative: Using sorted() Function
If you need to keep the original list unchanged and get a new sorted list, use the sorted() function instead ?
# Creating a List
names = ["Jacob", "Harry", "Mark", "Anthony"]
# Using sorted() to create a new sorted list
sorted_names = sorted(names)
print("Original List =", names)
print("New Sorted List =", sorted_names)
Original List = ['Jacob', 'Harry', 'Mark', 'Anthony'] New Sorted List = ['Anthony', 'Harry', 'Jacob', 'Mark']
Sorting Complex Data with sorted()
The sorted() function is particularly useful for sorting complex data structures like lists of dictionaries ?
# List of dictionaries
students = [
{"name": "Sam", "marks": 98},
{"name": "Tom", "marks": 93},
{"name": "Jacob", "marks": 97}
]
# Display the original data
print("Original data:")
for student in students:
print(student)
# Sorting by marks using lambda function
sorted_students = sorted(students, key=lambda item: item['marks'])
print("\nSorted by marks:")
for student in sorted_students:
print(student)
Original data:
{'name': 'Sam', 'marks': 98}
{'name': 'Tom', 'marks': 93}
{'name': 'Jacob', 'marks': 97}
Sorted by marks:
{'name': 'Tom', 'marks': 93}
{'name': 'Jacob', 'marks': 97}
{'name': 'Sam', 'marks': 98}
Comparison
| Method | Returns | Original List | Memory Usage |
|---|---|---|---|
list.sort() |
None |
Modified | Low (in-place) |
sorted() |
New sorted list | Unchanged | Higher (creates copy) |
Conclusion
Use list.sort() when you want to modify the original list in-place for memory efficiency. Use sorted() when you need to preserve the original list and work with a sorted copy.
