search

What is the difference between "sort" and "sorted" in Python?

In Python, both the sort() method and the sorted() function are used to sort elements in a list, but they have some key differences:

In-Place vs. New List:

  • sort(): The sort() method is a list method that sorts the elements of the list in-place, modifying the original list. It does not return a new list.
  • sorted(): The sorted() function takes an iterable as input and returns a new sorted list containing the elements of the iterable. The original iterable is not modified.

Return Value:

  • sort(): The sort() method does not return any value. It modifies the list in-place.
  • sorted(): The sorted() function returns a new list containing the sorted elements. The original iterable remains unchanged.

Usage:

  • sort(): The sort() method is used when you want to sort a list in-place, meaning you want to modify the original list itself.
  • sorted(): The sorted() function is used when you want to obtain a sorted version of an iterable without modifying the original iterable.

Here's an example to illustrate the difference between sort() and sorted():

my_list = [3, 1, 4, 2]

sorted_list = sorted(my_list)  # Returns a new sorted list
print(sorted_list)  # Output: [1, 2, 3, 4]
print(my_list)  # Output: [3, 1, 4, 2] (original list remains unchanged)

my_list.sort()  # Sorts the list in-place
print(my_list)  # Output: [1, 2, 3, 4]

In this example, sorted(my_list) returns a new list with the elements of my_list sorted in ascending order. The original my_list remains unchanged.

On the other hand, my_list.sort() sorts the elements of my_list in-place, modifying the original list itself. The result is the same sorted list [1, 2, 3, 4], but the modification happens directly on the original list.

It's worth noting that both sort() and sorted() provide optional parameters to customize the sorting behavior, such as specifying a custom sorting key or reverse sorting. Refer to the Python documentation for more details on these parameters.

In summary, use sort() when you want to sort a list in-place, modifying the original list, and use sorted() when you want to obtain a new sorted list while keeping the original iterable unchanged.

Related Questions You Might Be Interested