Ben Chuanlong Du's Blog

It is never too late to learn.

Sort Collections in Python

Tips

  1. You can use the built-in function sorted to sort any iterable collection. It always a (new) list containing sorted data. Some mutable collections (e.g., list) have thee method sort to sort elements in-place. Both sorted and Collection.sort accept an argument key for specifying customized sorting criteria.

Sort a List

In [18]:
my_list = [7, 1, 2, 3.1415 * 1.5]
my_list
Out[18]:
[7, 1, 2, 4.71225]

The function sorted returns a new sorted list.

In [19]:
sorted(my_list)
Out[19]:
[1, 2, 4.71225, 7]

sorted with a customized sorting criteria.

In [20]:
import math

sorted(my_list, key=lambda x: math.sin(x))
Out[20]:
[4.71225, 7, 1, 2]
In [21]:
my_list
Out[21]:
[7, 1, 2, 4.71225]

The method list.sort sorts the list in place.

In [22]:
my_list.sort()
my_list
Out[22]:
[1, 2, 4.71225, 7]
In [23]:
my_list.sort(key=lambda x: math.sin(x))
my_list
Out[23]:
[4.71225, 7, 1, 2]

Sort a Tuple

References

In [ ]:
 

Comments