Python list Method - sort()

www.‮igi‬ftidea.com

The sort() method in Python is used to sort the elements in a list in ascending order. The method modifies the original list in place and does not return anything.

The syntax for the sort() method is as follows:

list.sort(key=None, reverse=False)

Here, list refers to the list to be sorted. The key parameter is an optional function that is used to customize the sorting order. The reverse parameter is a Boolean value that is used to sort the list in descending order.

Example:

# Creating a list
my_list = [4, 2, 1, 3]

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

# Displaying the modified list
print(my_list)   # Output: [1, 2, 3, 4]

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

# Displaying the modified list
print(my_list)   # Output: [4, 3, 2, 1]

In the above example, the sort() method is first used to sort the list my_list in ascending order. The original list is modified and the output shows the sorted list. Then, the sort() method is used again to sort the list in descending order by setting the reverse parameter to True. The modified list is printed again to show the updated order of elements. It is important to note that the sort() method modifies the original list in place, so if you want to preserve the original list, you should make a copy of it before sorting.