In this tutorial, we will delve into the Python’s built-in
sort() method. This powerful function allows you to organize your data in a way that makes it easier to understand and analyze.
What is the sort() method?
sort() method in Python is used to sort elements of a list in either ascending order (default) or descending order. The syntax for using this function is as follows:
This method modifies the list it is called on.
Parameters of sort()
- key: This parameter serves as a basis for sort comparison. It requires a function to be sent as its argument.
- reverse: If set true, then the list elements are sorted in descending order.
A Basic Example of Using sort()
numbers = [4, 2, 9, 7] numbers.sort() print(numbers)
The output will be: [2, 4, 7, 9]
Tutorial: Sorting with Custom Function
You can also use custom functions as the key parameter. Let’s say we have a list of tuples where each tuple contains name and age. We want to sort this list by age. Here’s how you can do it:
def get_age(person): return person people = [("John", 20), ("Jane", 30), ("Dave", 25)] people.sort(key=get_age) print(people)
The output will be: [(‘John’, 20), (‘Dave’, 25), (‘Jane’, 30)]
Sorting in Descending Order
To sort the list in descending order, you can set the reverse parameter to True. Here’s an example:
numbers = [4, 2, 9, 7] numbers.sort(reverse=True) print(numbers)
The output will be: [9, 7, 4, 2]
In this tutorial, we’ve learned how to use Python’s
sort() method to sort lists in ascending and descending order. We also explored how to use custom functions as the key parameter for more complex sorting tasks.
This is just scratching the surface of what you can do with Python’s built-in methods. Keep exploring!