Skip to main content

sort() vs sorted()

list.sort() and sorted() look similar, but they behave differently in an important way. One mutates the original list and returns None. The other returns a new sorted result.

What is happening?

numbers = [3, 1, 2]
result = numbers.sort()

print(numbers)
print(result)

Output:

[1, 2, 3]
None

What you might expect: result holds the sorted list.

What actually happens: sort() changes numbers in place and returns None.

Why this matters

This design helps make mutation explicit. It prevents code from accidentally treating an in-place operation like a pure one.

The bug usually appears when code writes:

numbers = [3, 1, 2]
sorted_numbers = numbers.sort()

Now sorted_numbers is None.

Choose based on whether mutation is intended

Use sort() when you intentionally want to mutate the existing list:

numbers.sort()

Use sorted() when you want a new sorted value:

numbers = [3, 1, 2]
sorted_numbers = sorted(numbers)

Rules of thumb

  • sort() mutates a list and returns None.
  • sorted() returns a new sorted result.
  • Use sort() for intentional in-place mutation.
  • Use sorted() when you want to preserve the original data.