Sorting a Python List
To sort a list in Python, you can use the sort() method. This method sorts the elements of the list in place.
yourlist.sort()
The sort method arranges the elements in ascending order, either alphabetically or numerically.
Note: Sorting works only if the list contains homogeneous data, either all numeric or all alphanumeric. If the list contains mixed data types, the method will return an error.
Example
Let's create a list with the following elements:
year = [2011, 2010, 2013, 2012, 2014]
To sort the list in ascending order, apply the sort() method:
year.sort()
After running the command, the list will be:
year = [2010, 2011, 2012, 2013, 2014]
It's quite simple.
Sorting a List in Descending Order
To sort a list in descending order (from highest to lowest), you first sort the list in ascending order using the sort() method.
Then, you reverse the list using the reverse() method.
Example
Create a list with numbers in random order:
year = [2011, 2010, 2013, 2012, 2014]
Sort the list in ascending order using the sort() method:
year.sort()
Now the list will be:
year = [2010, 2011, 2012, 2013, 2014]
Then, use the reverse() method to invert the order of the elements:
year.reverse()
Now the list will be:
[2014, 2013, 2012, 2011, 2010]
This way, you have sorted the list in descending order.