DEV Community

guzmanojero
guzmanojero

Posted on

sorted() vs .sort() in Python: What’s the Difference?

If you've worked with lists in Python, you've probably come across both sorted() and .sort(). At first glance, they seem to do the same thing — sort data. But behind the scenes, they work quite differently.

Let’s break it down.


sorted() — Returns a New Sorted List

The sorted() in-built function can be used on any iterable: lists, tuples, dictionaries, etc. It doesn’t modify the original object. Instead, it returns a new sorted list.

# syntax:
sorted(iterable, key=None, reverse=False)

nums = [3, 1, 2]
sorted_nums = sorted(nums)

print(sorted_nums)  # [1, 2, 3]
print(nums)         # [3, 1, 2] — original list is unchanged
Enter fullscreen mode Exit fullscreen mode

You can also sort in reverse or customize sorting with the key argument:

names = ['Alice', 'bob', 'Charlie']
print(sorted(names, key=str.lower))  # ['Alice', 'bob', 'Charlie']
Enter fullscreen mode Exit fullscreen mode

.sort() — Sorts In-Place

The .sort() method is available only for lists. It modifies the list in place and returns None.

# syntax
list.sort(key=None, reverse=False)

nums = [3, 1, 2]
nums.sort()

print(nums)  # [1, 2, 3] — original list is changed
Enter fullscreen mode Exit fullscreen mode

Just like sorted(), .sort() also supports key and reverse:

words = ['banana', 'Apple', 'cherry']
words.sort(key=str.lower)
print(words)  # ['Apple', 'banana', 'cherry']
Enter fullscreen mode Exit fullscreen mode

⚖️ Key Differences at a Glance

Feature sorted() .sort()
Type Built-in function List method
Return value New sorted list None
Original list Unchanged Modified (in-place)
Usable on Any iterable Lists only

Sorting Trivia

Historically, the sorting algorithm used was called Timsort but since Python 3.11 it was replaced by an improved algorithm called Powersort which is based in Timsort.

Top comments (0)