Background:
From the very beginning, the Python language has provided built-in tools for sorting collections. The sort() method and the sorted() function appeared in the second version of Python, but starting from Python 2.4, sorted() was introduced as a universal tool for sorting any iterable objects (not just lists).
Problem:
Often, there is a need to sort data by different criteria, and it is not always desirable to modify the original object. Beginners often confuse sort() and sorted(), not understanding where each is applied, and make mistakes with the sorting key and reverse order.
Solution:
sorted(iterable, key=None, reverse=False) always returns a new list object without modifying the original.list.sort(key=None, reverse=False) sorts the list in place and returns None.key parameter is a function that determines the criterion for sorting.reverse=True changes the order to reverse.Example of sorting a list of strings by their length, in reverse order:
words = ['python', 'is', 'strong', 'language'] sorted_words = sorted(words, key=len, reverse=True) print(sorted_words) # ['language', 'python', 'strong', 'is']
Key features:
What does the sort() method return?
The list.sort() method sorts the list itself and always returns None, which is often forgotten.
lst = [3, 1, 2] res = lst.sort() print(res) # None print(lst) # [1, 2, 3]
Can a tuple be sorted using sort()?
No, tuples are immutable; they do not have a .sort() method. Use sorted() for sorting.
tuple_data = (5,2,3) sorted_tuple = sorted(tuple_data) print(sorted_tuple) # [2, 3, 5]
What happens if a function that returns different types is specified in key?
A TypeError will occur if the returned values are incomparable (for example, int and str).
During an interview, the candidate is asked to return a sorted list by length, and they do:
lst = ['one', 'elephant'] ans = lst.sort(key=len) print(ans) # None
Pros:
Cons:
Correct usage:
lst = ['one', 'elephant'] ans = sorted(lst, key=len) print(ans) # ['one', 'elephant']
Pros:
Cons: