The sort() method in Python is used to arrange the elements of a list in a specific order. It works only on lists, modifies the original list in place, and does not return a new list.
Example: This example shows the most basic use of sort() to arrange numbers in ascending order.
a = [5, 3, 8, 1, 2]
a.sort()
print(a)
Output
[1, 2, 3, 5, 8]
Explanation:
- a.sort() rearranges the elements of a in ascending order
- The original list a itself gets updated
Syntax
list.sort(key=None, reverse=False)
Parameters:
- key: A function that decides how elements are compared
- reverse: If True, sorts the list in descending order
Examples
Example 1: This example sorts a list of numbers from largest to smallest using the reverse parameter.
n = [4, 1, 9, 2]
n.sort(reverse=True)
print(n)
Output
[9, 4, 2, 1]
Explanation: reverse=True changes the sorting order to descending
Example 2: Here, the list is sorted based on the length of each string instead of alphabetical order.
w = ["sun", "moonlight", "sky"]
w.sort(key=len)
print(w)
Output
['sun', 'sky', 'moonlight']
Explanation: key=len tells sort() to compare items using their length
Example 3: This example sorts a list of dictionaries using the value of the "age" key.
p = [ {"name": "Jake", "age": 30},
{"name": "Joe", "age": 25},
{"name": "Justin", "age": 35} ]
p.sort(key=lambda x: x["age"])
print(p)
Output
[{'name': 'Joe', 'age': 25}, {'name': 'Jake', 'age': 30}, {'name': 'Justin', 'age': 35}]
Explanation:
- key=lambda x: x["age"] extracts the age value for comparison
- The list is sorted in ascending order of age
sort() vs sorted() function
Understanding the difference between sorted() and sort() helps you choose the right tool for your needs. Both sort elements but differ in memory usage, stability, and compatibility. Let’s break it down in the following table.
Feature | sorted() | sort() |
|---|---|---|
Return Type | Returns a new sorted list | Sorts the list in place |
Order | Can specify ascending/descending | Default is ascending |
Applicable to | Any iterable (not just lists) | Only lists |
Stability | Stable (maintains relative order) | May not be stable |
Memory Usage | Requires extra memory | Sorts in place, no extra memory |
Key Parameter | Supports key for custom sorting | Supports key for custom sorting |
Time Complexity | O(n log n) | O(n log n) |
Related Articles: