Sorting Lists in Python
Sorting is a fundamental concept in computer science and programming. It refers to the process of arranging a list or set of elements in a particular order, typically numerical or alphabetical.
The purpose of sorting is to rearrange data in a way that makes it easier to find, process, and analyze. In this article, we will explore list sorting in Python, a popular programming language used by many developers.
Example of sorting in real-life scenario
Before we dive into the details of list sorting in Python, let’s take a real-life example of sorting to understand the concept better. Consider a school’s student records.
The student records have various pieces of information such as name, age, class, grade, etc. If we organize the student records in simple chronological order, the list becomes quite cumbersome to process.
But, if we sort the student records by class, grade, or name, it becomes easier for administrators to view and work with the records.
Method to sort a list using sort()
Python provides a straightforward way to sort a list using the sort()
method. This method does not create a new list but rearranges the existing list elements to the desired order.
There are three parameters that can be passed to the sort()
method: ascending, descending, and key function. Let’s dive into the details of each.
Sorting the list elements in ascending order
Ascending order sorting refers to ordering elements from the smallest to the largest. In Python, the sort()
method sorts a given list in ascending order by default.
The syntax for this is quite simple:
list_name.sort()
Here, list_name
is the name of the list that we want to sort. Calling the sort()
method on the list_name
arranges its elements in ascending order.
If you want to print the new sorted list, you can use:
print(list_name)
Sorting the list elements in descending order
Descending order sorting refers to arranging the elements from the highest to the lowest. In Python, we can sort a list in descending order by specifying the reverse
parameter as True
in the sort
method.
Here is the syntax:
list_name.sort(reverse=True)
Here, reverse=True
sorts the list in descending order. Print the new sorted list using the print()
statement as shown earlier.
Sorting the list using a Key Function
Sometimes we might want to sort a list of complex items, such as a list of dictionaries or tuples. Python’s built-in sort
method has no idea how to compare such items.
In such cases, we need to use a Key Function to provide a sorting strategy to the sort()
method. A key function is a callable that returns a value that can be used for sorting.
You can create a key function that returns a specific attribute of an element to be sorted. For example, if we want to sort a list of tuples based on the first item in each tuple, we can do as follows:
def sort_key(t):
return t[0]
list_of_tuples.sort(key=sort_key)
Here, the sort_key()
function receives a tuple and returns its first element t[0]
.
The sort
method calls the key function once for each item to be sorted, and then it uses the function’s return value to determine the item’s place in the sorted list.
Sorting the list using User-Defined Order
Python allows us to sort a list in a specific order that we define yourself. Here is an example of how we can sort a list based on a predefined order.
list_of_colors = ['red', 'blue', 'green', 'yellow', 'purple']
def custom_order(value):
order = {'red': 1, 'green': 2, 'blue': 3, 'yellow': 4, 'purple': 5}
return order[value]
list_of_colors.sort(key=custom_order)
Here, we define a custom_order()
function that associates each color with a value, and then we pass the function to the sort()
method as a key function. The output of the sorted list will follow the predefined order defined in the custom_order()
function.
Sorting the list of Class Objects
Lastly, we will look at how to sort a list of Class objects. There are many possible ways to sort a list of Class objects.
The most common way to do this is to define a key function that returns the property you want to sort on. Here is a simple class to work with:
class Book:
def __init__(self, title, author, year_published):
self.title = title
self.author = author
self.year_published = year_published
list_of_books = [
Book('The Alchemist', 'Paulo Coelho', 1988),
Book('The Da Vinci Code', 'Dan Brown', 2003),
Book('Harry Potter and The Philosopher's Stone', 'J.K Rowling', 1997),
]
We can sort the list of books by year_published
as follows:
def sort_key(book):
return book.year_published
list_of_books.sort(key=sort_key)
Here, we define a function called sort_key
that takes a Book
object and returns its year_published
attribute.
We then pass this function as a key function to the sort
method. The output list will now be sorted based on the year_published
attribute.
Conclusion
In this article, we have covered different techniques for sorting lists in Python. Sorting is a critical operation in programming, and Python provides a comprehensive built-in sorting method with many flexible parameters.
The ability to rearrange data in a specific order is essential when working with large sets of data. By using the techniques we have discussed, you can sort data efficiently and make your code more robust and readable.
Explanation of the sort()
method and its Arguments
The sort()
method is a default method built into Python that sorts any given list in ascending order. The syntax for using the sort()
method is as follows:
list_name.sort()
The method rearranges the elements of list_name
and sorts them in ascending order.
For the sort()
method to work effectively, we need to understand some of the arguments that this method can take. These arguments can be used to customize how the elements in a list are sorted.
‘key’ Argument
The key
argument takes a function that is used to extract the key from each element in the list, which is then used as the basis for sorting. One application of this argument is sorting a list of tuples where we need to sort them based on a specific field.
We can use the key
argument to extract elements of a tuple that will be used as the basis for sorting.
Reversed()
The reversed()
argument is used to sort a list in descending order by reversing the sort order of the list. The syntax for reversing the order using the sorted()
method is as follows:
sorted(list_name, reverse=True)
Different Approaches to Sorting using the sort()
method
Sorting lists in Python can be done in several ways. The most common approaches include sorting in ascending order, sorting in descending order, sorting using a key function, sorting using user-defined order, and sorting lists of class objects.
Sorting in Ascending Order
When sorting a list in ascending order, the items are sorted in order from smallest to largest. As we saw earlier, this is the default sort order of the sort()
method in Python.
The syntax for sorting a list in ascending order is as follows:
list_name.sort()
Sorting in Descending Order
When sorting a list in descending order, the items are sorted in order from largest to smallest. We can achieve the reverse sorting order by using the reverse
parameter as True
in the sort()
method.
The syntax for sorting a list in descending order is as follows:
list_name.sort(reverse=True)
Sorting using a Key Function
When sorting a list of complex items such as a list of tuples, we need to use a key function to provide a specific sorting strategy. The key function is a callable that returns a value that can be used for sorting.
The syntax for sorting a list using a key function is as follows:
def sorting_key(item):
return item[1]
list_name.sort(key=sorting_key)
In this example, we have defined a function called sorting_key
that takes an item in the list as an input and returns the second value of the tuple as the key for sorting.
Sorting using User-Defined Order
Sorting using a user-defined order allows us to sort a list based on a predefined order that we define ourselves. We can associate each element in the list with a value and sort the list based on this association.
list_name = ['apple', 'banana', 'orange', 'grape']
def mapping_fun(value):
map_dict = {'apple': 10, 'banana': 20, 'orange': 30, 'grape': 40}
return map_dict[value]
list_name.sort(key = mapping_fun)
The mapping_fun()
function maps the elements to a specific value, which is then used as a key for sorting the list. The output list will be sorted based on the predefined value of each element in the list.
Sorting Lists of Class Objects
Python allows us to sort a list of class objects by defining a key function that returns the property that we want to sort the class objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person('John', 25)
person2 = Person('Anna', 30)
person3 = Person('Chris', 25)
person_list = [person1, person2, person3]
# Sort Person list based on age
def sorting_key(person):
return person.age
person_list.sort(key= sorting_key)
In this example, we have defined a class called Person
with properties name
and age
.
We then create an object of the Person
class and append it to the person_list
. We have used the sorting_key()
function to sort the Person
list based on the age of each object in the list.
Conclusion
List sorting is one of the most critical operations in programming. Python provides a built-in sort()
method that can sort lists in ascending order or descending order.
However, it’s not just limited to that. We can sort lists of complex objects or define our own sorting order using user-defined functions.
By knowing the different approaches to sorting lists, you can customize your code and implement the most appropriate strategy for your application. Sorting lists in Python is a fundamental concept that is critical when working with large sets of data.
The built-in sort()
method can sort lists in ascending or descending order and can use complex strategies such as key functions, user-defined orders, and sorting lists of class objects. By understanding the arguments of the sort()
method and the different approaches to sorting lists, developers can customize their code and create more efficient and readable programs.
With the importance of sorting in mind, it is essential to master the different strategies for sorting lists in Python in order to write effective and efficient code.