The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order.

The original list is not changed.

The sorted() function can be customized though optional arguments.

The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), makes it sort backwards.


Sorting Examples

How to use Sorting in Python

Create a list with some numbers in it 
numbers = [5, 1, 4, 3, 2, 6, 7, 9]

prints the numbers sorted
print sorted(numbers)

the original list of numbers are not changed
print numbers

my_string = ['aa', 'BB', 'zz', 'CC', 'dd', "EE"]

if no argument is used, it will use the default (case sensitive)
print sorted(my_string)

using the reverse argument, will print the list reversed
print sorted(strs, reverse=True)   ## ['zz', 'aa', 'CC', 'BB']

More Reading

Please see the python wiki for more things to do with sorting.

Leave a Reply

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