Python provides lists structures in order to hold multiple elements in a single variable like an array. Generally same type of data is hold in this elements and we may want to sort them for value or key, incremental or decrementally. In this tutorial we will examine sorting Python List structure in different ways.
Example Python List
Before starting examples with
sort operation we will create a simple list like below. This list consist of vowels as we can see below.
Sort List with sort() Function
In this example we will use
sort() function of the list which is names
mylist . After the sort operation the elements of the list will be sorted. So we will print list to see this .
mylist=['a','u','e','i'] mylist.sort() print(mylist)
Sort with sorted() Function
There is also separate function named
sorted() which accepts List type as parameter and return as a sorted List like below. We will provide
mylist and assign the sorted list as
mysortedlist like below.
mylist=['a','u','e','i'] sortedlist=sorted(mylist) print(sortedlist)
Sort Reverse Order with sorted() Function
We have also the ability to sort in reverse order. We will use the
reverse parameter with the
true value. So the sort operation will be made in reverse.
mylist=['a','u','e','i'] sortedlist=sorted(mylist,reverse=True) print(sortedlist)
Sort Reverse Order with sort Function
We can also use List structure
sort() function in order to sort in reverse order. This is very similar to the
mylist=['a','u','e','i'] mylist.sort(reverse=True) print(mylist)