Sorting sequences

In [9]:
greeks = ['Aeschylus', 'Sophocles', 'Socrates', 'Euripides', 'Phrynichus']

Get a sorted copy.

In [10]:
out = sorted(greeks)

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

Sort in place.

In [12]:
greeks.sort()

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

Change the sort direction.

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

Provide a function and sort by its output.

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

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

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