Python (Scripting) - Sort a List
by
Jeremy Canfield |
Updated: October 16 2023
| Python (Scripting) articles
sort can be used, as the name suggests, to sort a list of items. For example, let's say you have a list of fruits.
fruits = ["apple", "orange", "banana", "grapes"]
You can print the list.
print(fruits)
Which should return the following. Notice the list is not sorted alphabetically.
['apple', 'orange', 'banana', 'grapes']
sort by default will sort the list alphabetically.
fruits = ["apple", "orange", "banana", "grapes"]
fruits.sort()
print(fruits)
Which should now return the list sorted.
['apple', 'banana', 'grapes', 'orange']
reverse=True can be used to sort the list in reverse order alphabetically, from Z to A.
fruits.sort(reverse=True)
Did you find this article helpful?
If so, consider buying me a coffee over at