0
0
PythonComparisonBeginner · 3 min read

Sort vs sorted in Python: Key Differences and Usage

In Python, sort() is a list method that changes the original list order in place and returns None, while sorted() is a built-in function that returns a new sorted list without changing the original. Use sort() when you want to modify the list directly, and sorted() when you need a sorted copy.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of sort() and sorted() in Python.

Featuresort()sorted()
TypeList methodBuilt-in function
Modifies original list?Yes (in-place)No (returns new list)
Return valueNoneNew sorted list
Works on other iterables?No, only listsYes, any iterable
Syntax examplelist.sort()sorted(iterable)
Use caseWhen you want to change the list itselfWhen you want a sorted copy
⚖️

Key Differences

The sort() method is called on a list and changes that list directly. It does not create a new list and returns None to remind you that the original list is changed. This means after calling sort(), the original list is now sorted.

On the other hand, sorted() is a built-in function that accepts any iterable (like lists, tuples, or strings) and returns a new list with the elements sorted. The original data remains unchanged. This makes sorted() more flexible when you want to keep the original data intact.

Both accept optional arguments like key for custom sorting logic and reverse to sort descending. But remember, sort() only works on lists, while sorted() works on any iterable.

⚖️

Code Comparison

Here is how you use sort() to sort a list in place:

python
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers)
Output
[1, 2, 5, 9]
↔️

sorted() Equivalent

Here is how you use sorted() to get a new sorted list without changing the original:

python
numbers = [5, 2, 9, 1]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
print(numbers)  # original list unchanged
Output
[1, 2, 5, 9] [5, 2, 9, 1]
🎯

When to Use Which

Choose sort() when you want to sort a list and do not need to keep the original order. It is efficient because it sorts in place without extra memory.

Choose sorted() when you need a sorted version but want to keep the original data unchanged, or when working with other iterable types like tuples or strings.

In short, use sort() for in-place sorting of lists, and sorted() for creating sorted copies or sorting non-list iterables.

Key Takeaways

sort() changes the list itself and returns None.
sorted() returns a new sorted list and keeps the original unchanged.
sort() works only on lists; sorted() works on any iterable.
Use sort() for in-place sorting to save memory.
Use sorted() when you need a sorted copy or to sort non-list data.