You can use the sort() method for sorting lists inplace. The sorted() function can be used to get a sorted list from any iterable.

The key argument accepts the name of a function (i.e. function object) for custom sorting. If two elements are deemed equal based on the result of the function, the original order will be maintained (stable sorting). Here are some examples:

# based on the absolute value of an element
# note that the input order is maintained for all three values of "4"
>>> nums = [-1, -4, 309, 4.0, 34, 0.2, 4]
>>> nums.sort(key=abs)
>>> nums
[0.2, -1, -4, 4.0, 4, 34, 309]

# based on the length of an element
>>> words = ('morello', 'irk', 'fuliginous', 'crusado', 'seam')
>>> sorted(words, key=len, reverse=True)
['fuliginous', 'morello', 'crusado', 'seam', 'irk']

Here are some examples using lambda expressions:

# sorting dictionaries based on values
>>> vehicles = {'bus': 10, 'car': 20, 'jeep': 3, 'cycle': 5}
>>> sorted(vehicles, key=lambda k: vehicles[k])
['jeep', 'cycle', 'bus', 'car']
>>> dict(sorted(vehicles.items(), key=lambda t: t[1]))
{'jeep': 3, 'cycle': 5, 'bus': 10, 'car': 20}

# based on file extension
>>> files = ('report.txt', 'hello.py', 'calc.sh', 'tictactoe.py')
>>> sorted(files, key=lambda f: f.rsplit('.', 1)[-1])
['hello.py', 'tictactoe.py', 'calc.sh', 'report.txt']

info See also docs.python HOWTOs: Sorting.

Video demo:


info See also my 100 Page Python Intro ebook.