What Is the Difference Between `Sorted(List)` vs `List. Sort()`?
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...
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?
6 Answers
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.
What is the difference between
sorted(list)vslist.sort()?
list.sortmutates the list in-place & returnsNonesortedtakes any iterable & returns a new list, sorted.
sorted is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:
def sorted(iterable, key=None):
new_list = list(iterable) # make a new list
new_list.sort(key=key) # sort it
return new_list # return it
when to use which?
- Use
list.sortwhen you do not wish to retain the original sort order (Thus you will be able to reuse the list in-place in memory.) and when you are the sole owner of the list (if the list is shared by other code and you mutate it, you could introduce bugs where that list is used.) - Use
sortedwhen you want to retain the original sort order or when you wish to create a new list that only your local code owns.