Python List sort() Method
Description
sort()The function is used to sort the original list. If a parameter is specified, the comparison function specified by the parameter is used.
Syntax
sort() method syntax:
list.sort(cmp=None, key=None, reverse=False)
Parameters
- cmp -- Optional parameter. If specified, the method of this parameter will be used for sorting.
- key -- The element mainly used for comparison. It has only one parameter. The specific function's parameter is taken from the iterable object, specifying an element in the iterable object for sorting.
- reverse -- Sorting rule,reverse = Truedescending order,reverse = Falseascending order (default).
Return Value
This method has no return value, but it sorts the objects in the list.
Examples
The following examples demonstrate how to use the sort() function:
Examples
#!/usr/bin/python
# -*- coding: UTF-8 -*-
aList = ['123', 'Google', 'Example', 'Taobao', 'Facebook'];
aList.sort();
print("List : ")
print(aList)
The output of the above example is as follows:
List : ['123', 'Facebook', 'Google', 'Example', 'Taobao']
The following example outputs the list in descending order:
Examples
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# List
vowels = ['e', 'a', 'u', 'o', 'i']
# Descending order
vowels.sort(reverse=True)
# Output result
print('Descending output:')
print( vowels )
The output of the above example is as follows:
降序输出: ['u', 'o', 'i', 'e', 'a']
The following example demonstrates outputting a list by specifying the sorting of elements in the list:
Examples
#!/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
print('Sorted list:')
print(random)
The output of the above example is as follows:
排序列表: [(4, 1), (2, 2), (1, 3), (3, 4)]Other Extensions
Python Lists