Sort list in Python

Posted on Updated on

Python has different methods to sort elements of a list. These methods arrange elements in their natural order either in ascending or descending order. For example, if the elements are all integers, then smaller numbers go earlier in the list. If the elements are all strings, they are arranged in alphabetic order. Below are examples to sort list using list.sort(), sorted() method in ascending and descending order.

1) Sort list using list.sort()

list.sort() sorts the list in-place and returnsĀ none. So, you can’t retrieve the original positions once list.sort() has called. Below example demonstrate how to sort list using list.sort()

Output

2) Sort list using list.sort() in reverse order

You can use list.sort() method to sort list in reverse order as well. Below is the example to sort list in reverse order using list.sort() method.

Output

3) Sort list using sorted() method

Sorted creates a new list from the old and returns the new one. Below example demonstrate sort list using sorted() method.

Output

4) Sort list using sorted() method in reverse order

You can sort list in reverse order using sorted method by passing parameter reverse. By default the value of reverse is false. Below example demonstrate sort list using sorted() method in reverse order.

Output

Stay tuned for more updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.