Built-in Sorting Methods in Python
Python is a popular programming language for its simplicity and intuitive syntax, making it easy for new users to learn and adapt to the language. Sorting is a crucial aspect of every programming language, and Python offers various sorting functions or methods to sort data types based on certain criteria.
In this article, we will explore the most common built-in sorting methods in Python, their syntax, and how to implement these methods in sorting data types.
Sorted() function
The sorted() function is a built-in function in Python that sorts an iterable and returns a new sorted list. The sorted() function syntax is as follows:
sorted(iterable, *, key=None, reverse=False)
The iterable
argument refers to the items to be sorted, and the other two parameters are optional.
The key
parameter is an additional argument that can be used to specify a function of one argument to extract a comparison key from each element in the iterable. This key will be used to sort the items in the iterable.
If the key
parameter is not provided, the sorted()
function will sort the iterable items based on their value. The reverse
parameter is another optional parameter used to specify whether the sorted list should be in ascending or descending order.
If the reverse
parameter is set to True
, the sorted()
function returns the iterable in descending order. If not, it returns the iterable in ascending order, which is the default behavior.
Sort() method
The sort()
method is also a built-in method in Python. Unlike the sorted()
function that returns a new sorted list, the sort()
method sorts the items in place.
This means the original iterable is modified, and a new list is not returned. The syntax for the sort()
method is as follows:
list.sort(key=None, reverse=False)
The syntax is similar to the sorted()
function, where the key
and reverse
parameters are optional and work as described above.
Examples of Using Sorting Methods in Python
Sorting a List of Numbers
Consider the following example:
numbers = [5, 8, 1, 3, 7, 2]
sorted_numbers = sorted(numbers) # [1, 2, 3, 5, 7, 8]
numbers.sort(reverse=True) # [8, 7, 5, 3, 2, 1]
The first line in the example creates an unordered list of integers. To sort this list in ascending order, the sorted()
function is called on the numbers
list, which creates a new sorted list.
The original list is left unaffected. Alternatively, the sort()
method is called on the numbers
list, which sorts the list in place.
Here, reverse
is set to False
, resulting in an ascending sorted list. The second line sorts the list in descending order using the sort()
method.
The reverse
parameter is set to True
, which results in the list being sorted in descending order.
Sorting a List of Words Based on Length
Consider the following example:
words = ["dog", "cat", "elephant", "lion", "bear"]
sorted_words = sorted(words, key=len) # ['dog', 'cat', 'lion', 'bear', 'elephant']
words.sort(key=len, reverse=True) # ['elephant', 'lion', 'bear', 'dog', 'cat']
In this example, a list of words is created as an unordered list. To sort the list in ascending order based on the word’s length, the sorted()
function is called on the words
list.
The key
parameter is set to len
, which means the sorted list will be sorted by the word’s length. The second line sorts the words
list in descending order, again based on the key(len)
.
Also, the reverse
parameter is set to True
, which results in a descending order of words sorted based on length.
Conclusion
There you have it, two sorting methods in Python! Now you can easily sort the items in your data types based on specific criteria using the built-in Python sorting functions and methods. With a few optional parameters, the sorted()
function and the sort()
method can sort your data types as desired, whether in ascending or descending order.
With these methods, coding with Python just got a little bit easier!
Advantages and Differences between sorted() and sort() Methods
Sorting is an essential operation in programming that involves arranging data structures in a specific order. Python provides two built-in methods for sorting data types: the sorted()
function and the sort()
method.
While both methods offer similar functionality, they differ in their implementation, performance, and use case. In this article, we will explore the differences and advantages of using sorted()
and sort()
methods.
Sorted() Function
The sorted()
function is a Python built-in function that returns a new sorted list from an iterable without modifying the original iterable. The sorted()
function takes an iterable and two optional arguments: key
and reverse
.
The key
function is a callable that returns a single value, which determines the sort order. The reverse
argument is a boolean value that specifies whether to sort the items in ascending or descending order.
One of the significant advantages of the sorted()
function is that it offers a non-destructive way of sorting an iterable. This means that the original iterable remains unchanged, and the sorted items are returned as a new list.
As a result, the sorted()
function retains the original order of the iterable and doesn’t modify it. Let’s consider an example below:
fruits = ['apple', 'banana', 'orange', 'kiwi', 'pear']
sorted_fruits = sorted(fruits)
print(sorted_fruits)
# Output: ['apple', 'banana', 'kiwi', 'orange', 'pear']
In this example, we have an unordered list of fruits. We apply the sorted()
function on the fruits
list, which returns a new sorted list and assigns it to sorted_fruits
.
The output displays the sorted list in ascending order.
Sort() Method
The sort()
method is another built-in method that modifies the original list without creating a new list. The sort()
method sorts the elements in place, which means that the original items are modified, and there is no new list created.
The syntax of the sort()
method is as follows:
list.sort(key=None, reverse=False)
The key
parameter and the reverse
parameter have the same functionality as in the sorted()
function. One of the significant advantages of the sort()
method is that it sorts the iterable in place, which means it consumes less memory than the sorted()
function.
Additionally, the sort()
method is faster than the sorted()
function, especially for larger items. Let’s consider an example to illustrate the use of the sort()
method:
numbers = [5, 8, 1, 3, 7, 2]
numbers.sort()
print(numbers)
# Output: [1, 2, 3, 5, 7, 8]
In this example, we have an unordered list of numbers. Using the sort()
method, the numbers
list is sorted in ascending order.
Since the original list is modified, the output of the sorted list is displayed in place.
Custom Sorting Functions and Sorting in Descending Order
Python provides flexibility in sorting methods by allowing users to define their own sorting functions. Custom sorting functions allow developers to sort based on their specific criteria.
By using a custom sorting function, we can specify how we want to compare and sort our data. Let’s consider the following example to illustrate the use of custom sorting functions:
students = [('Tom', 19), ('Jane', 18), ('Alice', 20), ('Bob', 17)]
def sort_age(x):
return x[1]
sorted_students = sorted(students, key=sort_age)
print(sorted_students)
# Output: [('Bob', 17), ('Jane', 18), ('Tom', 19), ('Alice', 20)]
In this example, we have a list of tuples containing student names and ages. A custom sorting function sort_age()
is defined that returns the second item in each tuple, which represents the age.
The sorted()
function is called with our custom function as the key
argument. The output displays the sorted students by age in ascending order.
Sorting in descending order can be achieved by setting the reverse
argument to True
for both the sorted()
function and sort()
method. Let’s take a look at the example:
fruits = ['apple', 'banana', 'orange', 'kiwi', 'pear']
fruits.sort(reverse=True)
print(fruits)
# Output: ['pear', 'orange', 'kiwi', 'banana', 'apple']
In this example, we have an unordered list of fruits. The sort()
method is called on fruits
with the reverse
argument set to True
.
The output displays the sorted fruits in descending order.
Conclusion
The sorted()
function and the sort()
method are essential methods for sorting data structures in Python. The sorted()
function returns a new sorted list without modifying the original iterable, while the sort()
method sorts the original iterable in place, modifying the original order.
Python provides the flexibility of custom sorting functions, which allow users to sort based on their specific criteria. By knowing the differences and advantages between these methods, developers can choose the appropriate method to sort their data structures in Python.
In conclusion, sorting is a crucial operation in programming, and Python offers two built-in methods for sorting: the sorted()
function and sort()
method. The sorted()
function returns a new sorted list, leaving the original iterable unchanged, while the sort()
method sorts the original iterable in place, modifying its original order.
By using a custom sorting function, developers can sort based on specific criteria. The reverse
argument can be used to sort data structures in descending order.
Ultimately, understanding the differences, advantages, and use cases of each method can help developers choose the appropriate method for sorting their data types in Python. With the knowledge gained from this article, Python developers can properly implement sorting methods, save time, and write efficient code.