Python3 List sort() Method
Description
The sort() function sorts the original list; if a parameter is given, it uses the comparison function specified.
Syntax
sort() method syntax:
list.sort( key=None, reverse=False)
Parameters
Parameters
- 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
aList
=
[
'
'
,
'
Runoob
'
,
'
Taobao
'
,
'
'
]
aList
.
sort
(
)
(
"
List :
"
,
aList
)
The output of the above example is:
List : ['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:
降序输出: ['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
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:
排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)]
The Python3 list