alvas alvas - 2 months ago 12
Python Question

What is the difference between `sorted(list)` vs `list.sort()` ? python

list.sort()
sorts the list and save the sorted list, while
sorted(list)
returns a sorted list without changing the original list.


  • But when to use which?

  • And which is faster? And how much faster?

  • Can a list's original positions be retrieved after
    list.sort()
    ?


Answer

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices.

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. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() 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.

Comments