Sobes.tech
Junior — Middle

What distinguishes the built-in sort function from a method that returns a sorted copy of a collection?

sobes.tech AI

Answer from AI

In Python, there is a built-in list sorting method list.sort() and a function sorted() that returns a sorted copy of the collection.

  • list.sort() sorts the list in place, modifying the original object. It returns None.
  • sorted() accepts any iterable object and returns a new sorted list, leaving the original object unchanged.

Example:

lst = [3, 1, 2]
lst.sort()  # lst becomes [1, 2, 3]

lst = [3, 1, 2]
sorted_lst = sorted(lst)  # lst remains [3, 1, 2], sorted_lst = [1, 2, 3]

The choice depends on the task: if you need to modify the original list — use list.sort(), if you want to keep the original data and get a sorted version — use sorted().