Background:
The sort() method has been built into the list type since the early versions of Python, while the sorted() function appeared in Python 2.4. Sorting collections is one of the most common tasks in programming, and Python offers two main tools to solve it.
Problem:
Many beginners confuse sort() (the list method) and sorted() (the high-level function). There is a lack of understanding about when to use in-place sorting, which objects can be sorted, how to specify an arbitrary order through key/reverse, and the possible traps this leads to, especially for complex user-defined structures.
Solution:
list.sort() sorts the original list in place and returns None. It modifies the original object.sorted() returns a new sorted list (or another type if passed) without changing the original. It works with any iterable objects (even generators).key (sort function) and reverse (boolean flag for reverse sorting) parameters.Code example:
numbers = [5, 2, 9, 1] numbers.sort() # numbers = [1, 2, 5, 9] words = ['aaa', 'ZZZ', 'bbb'] sorted_words = sorted(words, key=str.lower, reverse=True) # sorted_words = ['ZZZ', 'bbb', 'aaa'] # words remains unchanged
Key features:
sort() works only for lists and sorts in place, while sorted() is more versatile — it works with any iterable object.What will the variable return if you do my_list = my_list.sort()?
Answer: my_list will be None, because sort sorts the list in place and returns None. This is a common bug: always sort in place without assignment, or use sorted if you need a sorted object as a new list.
Code example:
lst = [3, 1, 2] lst = lst.sort() # lst is now None
Can you sort a tuple or a string using the sort() method?
Answer: No, immutable objects (tuple, str) do not have a sort method, but sorted() applies to them, returning a new sorted list of the elements.
Code example:
tpl = (4, 2, 7) sorted_tpl = sorted(tpl) # sorted_tpl = [2, 4, 7]
Is it possible to sort a list with elements of different types?
Answer: In Python 3, sorting different incomparable types (e.g., int and str) raises TypeError. In Python 2 there was a specific order, now you need to explicitly specify the key function to generalize all values into a comparable form.
Negative Case
The programmer did my_list = my_list.sort(), after which they lost access to the original list because the variable was assigned the value None.
Pros:
Cons:
Positive Case
Used careful sorted() to get a new version without changing the original or correctly applied sort without assignment.
Pros:
Cons: