Usage of Python list sort method
Using the Python list sort method
1. Introduction
Python is an easy-to-learn programming language with a rich set of built-in functions and methods. Among them, the list is one of the most commonly used data types in Python, used to store an ordered set of elements. Lists provide a variety of methods for operating on lists, including the sort() method for sorting lists.
In this article, we’ll explore the usage of the Python list sort method, including syntax, parameters, and return values, and demonstrate its application through code examples.
2. Syntax
The syntax of the sort() method is as follows:
list.sort(key=..., reverse=...)
The sort() method operates on the list itself and does not return a value. It accepts two optional parameters: key and reverse.
- key: Specifies a function whose return value is used for sorting.
- reverse: Specifies the sorting order. Possible values are True or False. The default is False, indicating ascending sorting.
3. Example Code
The following example code demonstrates the use of the sort() method.
First, we create a list containing some numbers:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
3.1 Default Sorting
We can use the sort() method to sort the list in ascending order by default:
numbers.sort()
print(numbers)
Running result:
[1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
3.2 Descending Sort
To sort a list in descending order, we can set the reverse parameter to True:
numbers.sort(reverse=True)
print(numbers)
Result:
[9, 6, 5, 5, 4, 3, 3, 2, 1, 1]
3.3 Custom Sorting Function
The sort() method can also accept a key parameter, which specifies a function whose return value is to be used for sorting.
Suppose we have a list of strings that we want to sort by their length.
First, we define a function to get the length of a string:
def get_length(string):
return len(string)
Then, we use this function as the key parameter to sort:
strings = ["apple", "banana", "cherry", "date"]
strings.sort(key=get_length)
print(strings)
Result:
['date', 'apple', 'cherry', 'banana']
In this example, the get_length function returns the length of the string, and the sort() method sorts the strings based on their length.
4. Notes
When using the sort() method, be aware of some details:
- The sort() method changes the order of the original list and does not return a value.
- The sort() method can only be used on mutable lists, not on tuples or other immutable sequences.
- The sort() method uses Python’s default sorting rules by default, which sorts numbers by size and strings by lexicographical order.
5. Summary
This article introduced the use of the sort() method on lists in Python. We’ve learned the syntax, parameters, and return values of the sort() method, and demonstrated its specific application through example code. When using the sort() method, you can sort in ascending or descending order as needed, and you can also sort based on a custom function.