list.sort()
sorts the list and replaces the original list, whereas sorted(list)
returns a sorted copy of the list, without changing the original list.
- When is one preferred over the other?
- Which is more efficient? By how much?
- Can a list be reverted to the unsorted state after
list.sort()
has been performed?
Please use Why do these list operations (methods) return None, rather than the resulting list? to close questions where OP has inadvertently assigned the result of .sort()
, rather than using sorted
or a separate statement. Proper debugging would reveal that .sort()
had returned None
, at which point “why?” is the remaining question.
Advertisement
Answer
sorted()
returns a new sorted list, leaving the original list unaffected. list.sort()
sorts the list in-place, mutating the list indices, and returns None
(like all in-place operations).
sorted()
works on any iterable, not just lists. Strings, tuples, dictionaries (you’ll get the keys), generators, etc., returning a list containing all elements, sorted.
Use
list.sort()
when you want to mutate the list,sorted()
when you want a new sorted object back. Usesorted()
when you want to sort something that is an iterable, not a list yet.For lists,
list.sort()
is faster thansorted()
because it doesn’t have to create a copy. For any other iterable, you have no choice.No, you cannot retrieve the original positions. Once you called
list.sort()
the original order is gone.