This is my first time writing a blog in English, so please forgive me for not writing well
The sort()
method and sorted()
function in Python both sort elements, but they differ in usage and behavior:
1. Type and Usage:
-
sort()
:- A list method (only works with lists).
- Modifies the list in-place (changes the original list).
- Returns
None
. - Example:
python">numbers = [3, 1, 2] numbers.sort() # Original list is now sorted print(numbers) # Output: [1, 2, 3]
-
sorted()
:- A built-in function that works with any iterable (lists, tuples, dictionaries, etc.).
- Returns a new sorted list (original iterable remains unchanged).
- Example:
python">numbers = [3, 1, 2] sorted_numbers = sorted(numbers) # New sorted list print(sorted_numbers) # Output: [1, 2, 3] print(numbers) # Output: [3, 1, 2] (unchanged)
2. Return Value:
sort()
: ReturnsNone
(modifies the original list).sorted()
: Returns a new sorted list, regardless of the input iterable type.
Example with a tuple:python">my_tuple = (3, 1, 2) sorted_list = sorted(my_tuple) # Returns a list: [1, 2, 3] sorted_tuple = tuple(sorted(my_tuple)) # Convert to tuple: (1, 2, 3)
3. Flexibility:
sorted()
: Can sort any iterable (e.g., dictionaries return sorted lists of keys):python">my_dict = {3: 'a', 1: 'b', 2: 'c'} print(sorted(my_dict)) # Output: [1, 2, 3]
sort()
: Only available for lists.
4. Parameters:
Both accept key
and reverse
parameters for custom sorting
python"># Sort strings by length using sorted()
words = ["apple", "bat", "cherry"]
print(sorted(words, key=len, reverse=True)) # Output: ['cherry', 'apple', 'bat']
# Sort list in-place using sort()
words.sort(key=len)
print(words) # Output: ['bat', 'apple', 'cherry']
5. Performance:
sort()
: Slightly more memory-efficient for large lists (no copy created).sorted()
: Creates a new list, so it uses extra memory.
Summary:
Feature | sort() | sorted() |
---|---|---|
Applicability | Lists only | Any iterable (lists, tuples, dicts, etc.) |
Modifies Original | Yes (in-place) | No (returns new list) |
Return Value | None | New sorted list |
Memory Usage | More efficient for large lists | Creates a copy (uses more memory) |
Functional Use | Limited (method call) | Flexible (works in expressions) |
Keep it simple
Use sort()
to sort a list in-place.
Use sorted()
to get a sorted copy of any iterable.