Tips¶
- 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 methodsort
to sort elements in-place. Bothsorted
andCollection.sort
accept an argumentkey
for specifying customized sorting criteria.
Sort a List¶
In [18]:
my_list = [7, 1, 2, 3.1415 * 1.5]
my_list
Out[18]:
The function sorted
returns a new sorted list.
In [19]:
sorted(my_list)
Out[19]:
sorted
with a customized sorting criteria.
In [20]:
import math
sorted(my_list, key=lambda x: math.sin(x))
Out[20]:
In [21]:
my_list
Out[21]:
The method list.sort
sorts the list in place.
In [22]:
my_list.sort()
my_list
Out[22]:
In [23]:
my_list.sort(key=lambda x: math.sin(x))
my_list
Out[23]:
Sort a Tuple¶
References¶
In [ ]: