Python: sort() vs sorted()

In Python, sort() and sorted() are two different ways to sort elements in a list, tuple, or any iterable. They differ in how they work and their impact on the original data structure. Here’s a breakdown of the key differences between sort() and sorted():

  1. Mutability:
  • sort(): This method is called on a list in-place, meaning it modifies the original list directly and doesn’t return a new sorted list. It rearranges the elements within the existing list.
    my_list = [3, 1, 2]
    # my_list is now [1, 2, 3]
  • sorted(): The sorted() function, on the other hand, returns a new sorted list and leaves the original iterable unchanged. It doesn’t modify the input.
    my_list = [3, 1, 2]
    sorted_list = sorted(my_list)
    # my_list remains [3, 1, 2], sorted_list is [1, 2, 3]
  1. Return Value:
  • sort(): It returns None. Since it sorts the list in-place, there is no need to return a new list.
  • sorted(): It returns a new sorted list, leaving the original iterable intact.
  1. Applicability:
  • sort(): It is a method specific to lists. You can’t use it directly on other iterable types like tuples or strings. It only works on lists.
  • sorted(): It is a built-in function that can be applied to any iterable, not just lists. You can use it with tuples, strings, dictionaries, and other iterable types.
  1. Custom Sorting: Both sort() and sorted() allow you to specify custom sorting criteria using the key argument. You can pass a function to key that defines how the elements should be compared during sorting.
   words = ["banana", "apple", "cherry"]

   # Sorting by the length of the words
   # words is now ['apple', 'cherry', 'banana']

   sorted_words = sorted(words, key=lambda x: x[::-1])
   # sorted_words is now ['banana', 'cherry', 'apple']

In summary, sort() is used for in-place sorting of lists and doesn’t return a new sorted list. sorted() is a more versatile function that can be applied to various iterable types and returns a new sorted list without modifying the original iterable. The choice between them depends on whether you want to sort in-place or keep the original data unchanged.

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists, crafted with the affection and dedication they’ve shown. ❤️

Feedback Display