Difference Between sort() and sorted() in Python

Python provides two ways to sort elements in an iterable: sort() and sorted(). They differ in how they work and their impact on the original data structure.


1. Mutability

sort(): Modifies the original list in-place and does not return a new list.

my_list = [3, 1, 2]
my_list.sort()
# my_list is now [1, 2, 3]

sorted(): Returns a new sorted list without modifying the original iterable.

my_list = [3, 1, 2]
sorted_list = sorted(my_list)
# my_list remains [3, 1, 2], sorted_list is [1, 2, 3]

2. Return Value

  • sort(): Returns None since it sorts the list in-place.
  • sorted(): Returns a new sorted list.

3. Applicability

  • sort(): Works only on lists.
  • sorted(): Works on any iterable (e.g., lists, tuples, strings, dictionaries).

4. Custom Sorting

Both methods allow sorting based on custom criteria using the key argument.
Using sort() with a key function:

words = ["banana", "apple", "cherry"] 
words.sort(key=len) # Sorts by word length 
print(words) # Output: ['apple', 'cherry', 'banana']

Using sorted() with a custom key:

def reverse_word(word):
    return word[::-1]

words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=reverse_word)  # Sorts by reversed word
print(sorted_words)  # Output: ['banana', 'cherry', 'apple']

Summary

Featuresort()sorted()
Modifies Original List?✅ Yes❌ No
Return ValueNoneNew sorted list
Works on Lists?✅ Yes✅ Yes
Works on Other Iterables?❌ No✅ Yes (tuples, strings, etc.)
Allows Custom Sorting (key argument)?✅ Yes✅ Yes

When to use?

  • Use sort() when you want to modify a list in-place.
  • Use sorted() when you need a sorted version while keeping 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. ❤️

Feedback Display