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

list.sort(key=None, reverse=False)
  • 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 to True, the list elements are sorted in descending order. The default is False, 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

  1. Sorting a List in Ascending Order:

    my_list = [3, 1, 4, 1, 5, 9] my_list.sort() # Sorts the list in ascending order print(my_list) # Output: [1, 1, 3, 4, 5, 9]
  2. Sorting a List in Descending Order: You can sort in descending order by setting the reverse parameter to True:

    my_list = [3, 1, 4, 1, 5, 9] my_list.sort(reverse=True) # Sorts the list in descending order print(my_list) # Output: [9, 5, 4, 3, 1, 1]
  3. Sorting a List of Strings: The sort() method can also be used with lists of strings:

    fruits = ['banana', 'apple', 'cherry'] fruits.sort() # Sorts the list in ascending order (alphabetically) print(fruits) # Output: ['apple', 'banana', 'cherry']
  4. 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:

    my_list = [(1, 'one'), (3, 'three'), (2, 'two')] my_list.sort(key=lambda x: x[1]) # Sorts based on the second element of each tuple print(my_list) # Output: [(1, 'one'), (3, 'three'), (2, 'two')]
  5. Sorting a List of Mixed Data Types: The sort() method raises a TypeError if you try to sort a list containing mixed data types that are not directly comparable:

    mixed_list = [1, 'banana', 3.14] try: mixed_list.sort() # Attempting to sort mixed types except TypeError as e: print(e) # Output: '<' not supported between instances of 'str' and 'int'
  6. Sorting with Custom Logic: You can create complex sorting logic using the key parameter. For example, sorting a list of strings by their length:

    words = ['banana', 'apple', 'kiwi', 'cherry'] words.sort(key=len) # Sorts based on the length of each word print(words) # Output: ['kiwi', 'apple', 'banana', 'cherry']

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 the reverse parameter enables descending order sorting.
  • It's essential to ensure that the list contains comparable elements; otherwise, a TypeError will occur.