The sort function is available in Python lists, which sort()
list items alphabetically.
List items sorted by default in ascending order when using the sort()
function.
colors_list = ["Red", "Blue", "Green"]
colors_list.sort()
print(colors_list)
['Blue', 'Green', 'Red']
In the above example, we sorted the list items using the sort()
function. As you can see in the output, the list items are sorted alphabetically from A to Z.
numbers_list = [50, 55, 40, 55, 99, 5, 10, 22]
numbers_list.sort()
print(numbers_list)
[5, 10, 22, 40, 50, 55, 55, 99]
We sorted the numeric list items using the sort()
function. As you can see in the output, the list items are sorted numerically in ascending order.
When you want to sort list items in descending order, pass the reverse = True
keyword argument in the sort function.
colors_list = ["Red", "Blue", "Green"]
colors_list.sort(reverse = True)
print(colors_list)
['Red', 'Green', 'Blue']
In the above example, we sorted the list items using the sort()
function, but we passed reverse = True
as an input argument to the sort function. Because of reverse = True
, the list sort in reverse order from Z to A.
numbers_list = [50, 55, 40, 55, 99, 5, 10, 22]
numbers_list.sort(reverse = True)
print(numbers_list)
[99, 55, 55, 50, 40, 22, 10, 5]
Similarly, we sorted numeric values in reverse order to pass the reverse = True
input argument in the sort()
function. As you can see in the output, the list items are sorted numerically in descening order.
By default, alphabetic text lists to sort by case sensitive in the sort()
function, so capital letter texts sort before small letter texts.
colors_list = ["Red", "blue", "Green", "orange"]
colors_list.sort()
print(colors_list)
['Green', 'Red', 'blue', 'orange']
In the above example, you can see the output, the capital letter color texts sorted before the small letter color texts.
If you want to sort alphabetic text lists without case sensitivity, then pass the key = str.lower
as an input argument to the sort()
function.
colors_list = ["Red", "blue", "Green", "orange"]
colors_list.sort(key = str.lower)
print(colors_list)
['blue', 'Green', 'orange', 'Red']
In the output, the color list sort order is case-insensitive.
You can also pass the customize function to the sort function as a keyword argument.
def lower_text(text):
return text.lower()
colors_list = ["Red", "blue", "Green", "orange"]
colors_list.sort(key = lower_text)
print(colors_list)
['blue', 'Green', 'orange', 'Red']
In the above example, we passed the lower_text()
function to the sort()
function as a keyword argument for case-insensitive sorting.