How to Sort Python List?

Python – Sort List

To sort a python list in ascending or descending order, you can use sort() method of List class.

In this tutorial, we shall use sort() function and sort the given list in ascending or descending order.

Syntax of list.sort()

The syntax of sort() method is:

mylist.sort(*, key=None, reverse=False)

where

Examples

1. Sort a list in ascending order

To sort a list in ascending order, you just have to call sort() method on the list without any arguments. In the following example, we have a list of numbers. We will arrange the items of this list in ascending order.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52]

mylist.sort()

print(mylist)
Run Code

Output

[5, 8, 21, 21, 52, 52, 87]

The default behavior of sort() function is to arrange the items in ascending order.

2. Sort a list in descending order

To sort a list in descending order, you can to pass reverse=True argument to the sort() function.

Python Program

mylist = [21, 5, 8, 52, 21, 87, 52]

mylist.sort(reverse=True)

print(mylist)
Run Code

Output

[87, 52, 52, 21, 21, 8, 5]

Summary

In this tutorial of Python Examples, we learned how to sort a Python list, with the help of well detailed example programs.

Related Tutorials

Privacy Policy Terms of Use

SitemapContact Us