Python List sort() method
Description
sort() The function sorts the original list. If a parameter is specified, it is sorted using the comparison function specified by that parameter.
Syntax
sort() method syntax:
list.sort(cmp=None, key=None, reverse=False)
Parameters
- cmp -- optional parameter; if specified, the list is sorted using the method of this parameter.
- 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
This method has no return value, but sorts the objects in the list.
Example
The following example shows how to use the sort() function:
Example
#!/usr/bin/python
-- coding: UTF-8 --
aList
=
[
'
123
'
,
'
'
,
'
Runoob
'
,
'
Taobao
'
,
'
'
]
;
aList
.
sort
(
)
;
(
"
List :
"
)
(
aList
)
The output of the above example is:
List :
['123', 'Facebook', 'Google', 'Runoob', 'Taobao']
The following example outputs the list in descending order:
Example
#!/usr/bin/python
-- coding: UTF-8 --
List
vowels
=
[
'
e
'
,
'
a
'
,
'
u
'
,
'
o
'
,
'
i
'
]
Descending
vowels
.
sort
(
reverse
=
True
)
Output result
(
'
Descending output:
'
)
(
vowels
)
The output of the above example is:
# Descending order output:
['u', 'o', 'i', 'e', 'a']
The following example shows how to output a list sorted by a specified element of its items:
Example
#!/usr/bin/python
-- coding: UTF-8 --
Get the second element of the list
def
takeSecond
(
elem
)
:
return
elem
[
1
]
List
random
=
[
(
2
,
2
)
,
(
3
,
4
)
,
(
4
,
1
)
,
(
1
,
3
)
]
Sort by the second element
random
.
sort
(
key
=
takeSecond
)
Output category
(
'
Sorted list:
'
)
(
random
)
The output of the above example is:
Sort list:
[(4, 1), (2, 2), (1, 3), (3, 4)]
Python Lists