Sorting sequences

greeks = ['Aeschylus', 'Sophocles', 'Socrates', 'Euripides', 'Phrynichus']

Get a sorted copy.

out = sorted(greeks)

print(greeks)
print(out)
['Aeschylus', 'Sophocles', 'Socrates', 'Euripides', 'Phrynichus']
['Aeschylus', 'Euripides', 'Phrynichus', 'Socrates', 'Sophocles']

Sort in place.

greeks.sort()

print(greeks)
['Aeschylus', 'Euripides', 'Phrynichus', 'Socrates', 'Sophocles']

Change the sort direction.

sorted(greeks, reverse=True)
['Sophocles', 'Socrates', 'Phrynichus', 'Euripides', 'Aeschylus']

Provide a function and sort by its output.

sorted(greeks, key=len)
['Socrates', 'Aeschylus', 'Euripides', 'Sophocles', 'Phrynichus']
sorted(greeks, key=lambda x: x[1])
['Aeschylus', 'Phrynichus', 'Socrates', 'Sophocles', 'Euripides']

Unlike sort, sorted can also be applied to immutable sequences (returning a list).

a = (11,4,15,6,13,12,4,5,1,0)
sorted(a)
[0, 1, 4, 4, 5, 6, 11, 12, 13, 15]

If you spot any errors please let me know on twitter.