Python list.sort() function
The list.sort()
method in Python is used to sort the elements of a list in ascending order by default. This method modifies the original list in place and does not return a new list.
Syntax
- Parameters:
key
(optional): A function that serves as a key for the sorting comparison. This function takes a single argument and returns a value to be used for sorting.reverse
(optional): A boolean value. If set toTrue
, the list elements are sorted in descending order. The default isFalse
, meaning the elements are sorted in ascending order.
Return Value
- The method does not return a value (
None
is returned implicitly) and modifies the original list.
Example Usage
Sorting a List in Ascending Order:
Sorting a List in Descending Order: You can sort in descending order by setting the
reverse
parameter toTrue
:Sorting a List of Strings: The
sort()
method can also be used with lists of strings:Using the Key Parameter: You can use the
key
parameter to sort the list based on specific criteria. For example, sorting a list of tuples based on the second element:Sorting a List of Mixed Data Types: The
sort()
method raises aTypeError
if you try to sort a list containing mixed data types that are not directly comparable:Sorting with Custom Logic: You can create complex sorting logic using the
key
parameter. For example, sorting a list of strings by their length:
Summary
list.sort(key=None, reverse=False)
is a powerful method for sorting lists in Python.- It modifies the original list in place and does not return a new list.
- The optional
key
parameter allows for custom sorting criteria, and thereverse
parameter enables descending order sorting. - It's essential to ensure that the list contains comparable elements; otherwise, a
TypeError
will occur.