The sort method
The sort
method sorts the elements of a list alphabetically in ascending order.
The first optional parameter of the method can be reverse
, which specifies the sorting direction. By default, it has the value False
.
In the second optional parameter, you can specify a callback function with sorting criteria.
Syntax
list.sort([list reversal mode], [function for sorting])
Example
Let's sort our list in reverse order:
lst = ['c', 'a', 'd', 'b', 'f', 'e']
lst.sort(reverse=True)
print(lst)
Result of code execution:
['f', 'e', 'd', 'c', 'b', 'a']
Example
Now let's sort the list of numbers in reverse order:
lst = [10, 8, 2, 6, 14]
lst.sort(reverse=True)
print(lst)
Result of code execution:
[14, 10, 8, 6, 2]
Example
Let's sort our list of letters without specifying the reverse parameter in the sort
method:
lst = ['c', 'a', 'd', 'b', 'f', 'e']
lst.sort()
print(lst)
Result of code execution:
['a', 'b', 'c', 'd', 'e', 'f']
Example
Now let's sort the list of numbers:
lst = [10, 8, 2, 6, 14]
lst.sort()
print(lst)
Result of code execution:
[2, 6, 8, 10, 14]