Python 3 – List sort() Method
The sort()
method in Python 3 is used to sort the elements of a list in ascending or descending order. This method changes the original list and does not create a new one. The syntax of the sort()
method is as follows:
list_name.sort(reverse = False)
In this syntax, list_name
is the name of the list that you want to sort, and reverse
is an optional parameter that you can use to specify the order in which you want to sort the elements. If you set reverse
to False
(which is the default value), the elements will be sorted in ascending order. If you set reverse
to True
, the elements will be sorted in descending order.
Sort a List in Ascending Order
Let’s see an example of how to use the sort()
method to sort a list in ascending order.
fruits = ['banana', 'orange', 'apple', 'kiwi', 'grape']
fruits.sort()
print(fruits)
Output:
['apple', 'banana', 'grape', 'kiwi', 'orange']
In this example, we have a list of fruits that we want to sort in ascending order. We call the sort()
method on the list and print the sorted list.
Sort a List in Descending Order
Now let’s see an example of how to use the sort()
method to sort a list in descending order.
fruits = ['banana', 'orange', 'apple', 'kiwi', 'grape']
fruits.sort(reverse = True)
print(fruits)
Output:
['orange', 'kiwi', 'grape', 'banana', 'apple']
In this example, we set the reverse
parameter to True
to sort the list in descending order.
Custom Sorting
You can also use the sort()
method to sort a list based on a custom key function. The key function is a function that takes an element of the list as input and returns a value that is used to sort the elements.
Let’s see an example of how to use the sort()
method to sort a list of tuples based on the second element of each tuple.
students = [('John', 90), ('Paul', 82), ('George', 95), ('Ringo', 77)]
students.sort(key = lambda x: x[1])
print(students)
Output:
[('Ringo', 77), ('Paul', 82), ('John', 90), ('George', 95)]
In this example, we have a list of tuples, where each tuple represents a student and their grade. We want to sort the list based on the students’ grades, so we pass a lambda function as the key parameter that returns the second element of each tuple.
Conclusion
The sort()
method in Python 3 is a useful method for sorting the elements of a list in ascending or descending order. You can also use a custom key function to sort the list based on a specific criterion. Keep in mind that the sort()
method changes the original list and does not create a new one.