Bootstrap FreeKB - Python (Scripting) - Sort a List
Python (Scripting) - Sort a List

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 802ee1 in the box below so that we can be sure you are a human.