Index
Definition
The sort()
method sorts the items of a list in ascending or descending order.
Syntax
The syntax of the sort()
method is:
Alternatively, you can also use built-in Python sorted() Function for the same purpose.
Note
The simplest difference between
sort()
andsorted()
is:sort()
changes the list directly and doesn’t return any value, whilesorted()
doesn’t change the list and returns the sorted list.
Parameter Values
Parameter | Description |
---|---|
iterable | Iterator objects that will be joined together |
reverse (Optional) | If True , the sorted list is reversed (or sorted in descending order). Defaults to False if not provided. |
key (Optional) | A function that serves as a key for the sort comparison. Defaults to None . |
Return Values
-
The
sort()
method doesn’t return any value. Rather, it changes the original list. -
If you want a function to return the sorted list rather than change the original list, use
sorted()
.
**Example 1) Sort a given list:
**Example 2) Sort in Descending order:
Setting reverse = True
sorts the list in the descending order.
key Parameter in Python sort()
If you want your own implementation for sorting, the sort()
method also accepts a key
function as an optional parameter.
Example using len() function has a key parameter:
- Here,
len
is Python’s in-built function to count the length of an element. - The list is sorted based on the length of each element, from lowest count to highest.
Particular examples
Read: Examples to see more interesting and powerful examples