In this tutorial, we will delve into one of Python’s most useful built-in methods –
sort(). This method is used to sort elements in a list in either ascending order (default) or descending order.
How to Use the sort() Method
The syntax for the
sort() method is as follows:
This method doesn’t return any value but it changes the original list.
- key: Primarily used as a basis for sort comparison. Default value is None.
- reverse: If set true, then the list elements are sorted in descending order. Default is False which means it will sort in ascending order.
An Example of Using sort()
numbers = [6, 9, 3, 1] numbers.sort() print(numbers) # Output: [1, 3, 6, 9]
In this example, we have a list of numbers that we want to arrange in ascending order. By calling
numbers.sort(), Python sorts our list from smallest to largest number.
Sorting In Descending Order
numbers = [6, 9, 3, 1] numbers.sort(reverse=True) print(numbers) # Output: [9, 6, 3, 1]
To sort our list in descending order instead of ascending order we use ‘reverse=True’.
Sorting Using a Key
key parameter allows us to base our sorting on a function. Let’s see an example:
words = ['apple', 'banana', 'cherry'] words.sort(key=len) print(words) # Output: ['apple', 'cherry', 'banana']
In this case, we’re sorting the list based on the length of each word.
sort() method is a powerful tool that can help you manipulate and organize your data effectively. Whether you’re working with numbers or strings, understanding how to use this method will undoubtedly enhance your Python programming skills.