Python sorted() Function
Description
sorted() The function sorts all iterable objects.
Difference between sort and sorted:
sort is a method applied to list, while sorted can sort any iterable object.
The sort method of list operates on the existing list and returns no value, whereas the built-in sorted function returns a new list rather than operating on the original.
Syntax
sorted syntax:
sorted(iterable, cmp=None, key=None, reverse=False)
Parameter Description:
- iterable -- an iterable object.
- cmp -- a comparison function with two arguments whose values are taken from the iterable. The function must follow these rules: return 1 if greater than, -1 if less than, and 0 if equal.
- key -- the element used for comparison; it takes a single argument, taken from the iterable, and specifies one element of the iterable to sort by.
- reverse -- sorting rule; reverse = True for descending, reverse = False for ascending (the default).
Return Value
Returns the reordered list.
Example
The following examples demonstrate how to use sorted:
a
=
[
5
,
7
,
6
,
3
,
4
,
1
,
2
]
b
=
sorted
(
a
)
Keep the original list
a
[
5
,
7
,
6
,
3
,
4
,
1
,
2
]
b
[
1
,
2
,
3
,
4
,
5
,
6
,
7
]
L
=
[
(
'
b
'
,
2
)
,
(
'
a
'
,
1
)
,
(
'
c
'
,
3
)
,
(
'
d
'
,
4
)
]
sorted
(
L
,
cmp
=
lambda
x
,
y
:
cmp
(
x
[
1
]
,
y
[
1
]
)
)
Using the cmp function
[
(
'
a
'
,
1
)
,
(
'
b
'
,
2
)
,
(
'
c
'
,
3
)
,
(
'
d
'
,
4
)
]
sorted
(
L
,
key
=
lambda
x
:
x
[
1
]
)
Using key
[
(
'
a
'
,
1
)
,
(
'
b
'
,
2
)
,
(
'
c
'
,
3
)
,
(
'
d
'
,
4
)
]
students
=
[
(
'
john
'
,
'
A
'
,
15
)
,
(
'
jane
'
,
'
B
'
,
12
)
,
(
'
dave
'
,
'
B
'
,
10
)
]
sorted
(
students
,
key
=
lambda
s
:
s
[
2
]
)
Sort by age
[
(
'
dave
'
,
'
B
'
,
10
)
,
(
'
jane
'
,
'
B
'
,
12
)
,
(
'
john
'
,
'
A
'
,
15
)
]
sorted
(
students
,
key
=
lambda
s
:
s
[
2
]
,
reverse
=
True
)
In descending order
[
(
'
john
'
,
'
A
'
,
15
)
,
(
'
jane
'
,
'
B
'
,
12
)
,
(
'
dave
'
,
'
B
'
,
10
)
]
Python built-in function