Sort vs sorted in Python: Key Differences and Usage
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.
| Feature | sort() | sorted() |
|---|---|---|
| Type | List method | Built-in function |
| Modifies original list? | Yes (in-place) | No (returns new list) |
| Return value | None | New sorted list |
| Works on other iterables? | No, only lists | Yes, any iterable |
| Syntax example | list.sort() | sorted(iterable) |
| Use case | When you want to change the list itself | When 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:
numbers = [5, 2, 9, 1] numbers.sort() print(numbers)
sorted() Equivalent
Here is how you use sorted() to get a new sorted list without changing the original:
numbers = [5, 2, 9, 1] sorted_numbers = sorted(numbers) print(sorted_numbers) print(numbers) # original list unchanged
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.sort() for in-place sorting to save memory.sorted() when you need a sorted copy or to sort non-list data.