**Python --sorted()**
sorted()
and sort()
:
sort()
is only for list, whilesorted()
can sort all iterable objects.sort()
has not return value, sorting the original list,sorted
will return a new sorted list, and the original list stay unchanged.
Definition:
sorted(iterable[, cmp[, key[, reverse]]])
note: arguments in []
are optional. And python3 doesn’t have cmp
argument anymore.
iterable
: iterable objects, likelist
,dict
,set
.cmp
: a custom comparison function. The default value isNone
.key
: specifies a function of one argument that is used to compare. The default value isNone
(compare the elements directly).reverse
: a boolean value. The default value isFalse
(ascending order). If you want descending order, setreverse = True
.
Usage:
Sort multiple dimensional lists:
1 | l = [(1,'a'), (2,'v'), (4, 'd'), (3, 's')] |
The usage of key
:
1 | sorted(l, key = len) # sort list according to the length of elements |