List sort() Method in Python

Python List sort() Method

The sort() method is used to sort the elements of a list in ascending order. It is a built-in method available for lists in Python.

Syntax of the sort() method:

list_name.sort()
  • list_name: This is the name of the list that you want to sort.

The sort() method modifies the original list in place, meaning it does not create a new list with the sorted elements. Instead, it directly rearranges the elements within the existing list so that they are in ascending order.

Example:

# Create a list
my_list = [5, 2, 8, 1, 3]

# Sort the list in ascending order
my_list.sort()

print(my_list)  # Output: [1, 2, 3, 5, 8]

As you can see, the sort() method arranged the elements of the original list in ascending order.

It's important to note that the sort() method only works for lists that contain elements of the same type or elements that are comparable. If your list contains a mixture of data types that are not comparable, the sort() method will raise a TypeError.If you need to sort the list in descending order, you can use the reverse parameter of the sort() method:

# Create a list
my_list = [5, 2, 8, 1, 3]

# Sort the list in descending order
my_list.sort(reverse=True)

print(my_list)  # Output: [8, 5, 3, 2, 1]

In this example, setting reverse=True as an argument to the sort() method sorts the list in descending order. The original list is modified accordingly.