Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

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

my_list = [7, 1, 2, 3.1415 * 1.5]
my_list
[7, 1, 2, 4.71225]

The function sorted returns a new sorted list.

sorted(my_list)
[1, 2, 4.71225, 7]

sorted with a customized sorting criteria.

import math

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

The method list.sort sorts the list in place.

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

Sort a Tuple

References