Understanding Sorted vs Sort in Python

Python Nov 26, 2023

Python, known for its ease of use and powerful data manipulation capabilities, offers two common ways to sort collections: the sorted() function and the sort() method. While they both serve the purpose of arranging data in a specified order, their usage, behavior, and effects differ significantly.

1. sorted() Function

The sorted() function is a built-in Python function that returns a new sorted list from the elements of any iterable (like lists, tuples, dictionaries).

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

print("Original:", numbers)
print("Sorted:", sorted_numbers)

2. sort() Method

The sort() method is specific to list objects in Python. It modifies the list it is called on and does not return a new list.

numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()

print("Sorted:", numbers)

Comparison Between sorted() and sort()

  • Return Type: sorted() returns a new list, whereas sort() does not return anything (it returns None).
  • Applicability: sorted() can be applied to any iterable, while sort() is only applicable to lists.
  • Impact on Original Data: sort() changes the original list, but sorted() leaves the original data unchanged.

When to Use Which?

  • Use sorted() when:
  • You need to sort different types of iterables, not just lists.
  • You want to maintain the original order of your data and require a sorted copy.
  • You're working with immutable data types (like tuples or strings).
  • Use sort() when:
  • You're only dealing with a list and want to sort it in place to optimize memory usage.
  • You don’t need to preserve the original order of your list.

Tags