What is the difference between list.sort() and sorted() in Python?
list.sort() sorts the list in place and returns None. sorted() accepts any iterable, leaves the original unchanged and returns a new sorted list. Both are stable and accept key and reverse arguments.
Explain it simply
sort() is rearranging the books on your own shelf. sorted() is photocopying the shelf order onto a fresh list, leaving your shelf as it was. Because it returns a copy, sorted also works on tuples, sets, strings and dictionary keys, which have no sort method.
Sorting is stable: items that compare equal keep their original relative order, which is what lets you sort by one field and then by another.
Example
marks = [72, 95, 60]
print(sorted(marks)) # Output: [60, 72, 95]
print(marks) # Output: [72, 95, 60]
print(marks.sort()) # Output: None
print(marks) # Output: [60, 72, 95]
students = [("Asha", 80), ("Dev", 95), ("Ira", 80)]
print(sorted(students, key=lambda s: s[1], reverse=True))
# Output: [('Dev', 95), ('Asha', 80), ('Ira', 80)]
print(sorted("banana")) # Output: ['a', 'a', 'a', 'b', 'n', 'n']What to say in the interview
"sort() mutates the list and returns None; sorted() returns a new list from any iterable. Both use Timsort, O(n log n), and are stable. I pass key for custom ordering, such as key=len or a lambda, and reverse=True for descending order."
Common mistakes
- Writing
lst = lst.sort()and ending up withNone.