Python List Sorting: sort() and sorted()

Introduction

Python lists are a versatile data structure that can hold different types of elements such as integers, strings, and even other lists. Sorting is a common operation performed on lists to arrange the elements in a particular order.

The built-in `sort()` function is the most commonly used method to sort a list in Python. However, there are alternative methods that can be used to sort a list in different ways.

In this blog post, we will explore some of the alternative methods to sort a list in Python. These methods include using the `sorted()` function, using lambda functions with `sort()`, and implementing custom sorting algorithms.

By the end of this post, you will have a better understanding of how to sort lists in Python beyond the traditional `sort()` function.

The Basics of List Sorting

Python lists are a versatile and powerful data structure that can store a collection of items. Sorting a list is a common operation, and there are various ways to achieve it in Python. One of the most straightforward methods is using the built-in sort() function.

The sort() function sorts the list in ascending order by default. Here’s an example:


numbers = [5, 1, 3, 2, 4]
numbers.sort()
print(numbers)

Output:


[1, 2, 3, 4, 5]

As you can see, the sort() function modifies the original list and returns None. If you want to sort the list in descending order, you can pass the reverse=True argument to the sort() function:


numbers = [5, 1, 3, 2, 4]
numbers.sort(reverse=True)
print(numbers)

Output:


[5, 4, 3, 2, 1]

Note that the reverse parameter is optional and defaults to False. Also note that sorting a list of strings follows a different rule than sorting integers or floats. In alphabetical order ‘a’ comes before ‘b’, so “apple” comes before “banana”.

In conclusion, using the sort() function is the easiest way to sort a Python list. It’s fast and efficient for small to medium-sized lists. However, for larger lists or more complex sorting needs we might want to explore other alternatives such as sorted(), which we will cover in another blog post.

The Alternative to the Sort Function

Python provides a built-in function called `sorted()` that can be used to sort lists. This function returns a new sorted list and does not modify the original list. Here’s an example:


numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

The `sorted()` function can also take a custom key function as an argument. This key function takes an element from the list and returns a value that will be used as the sorting key. Here’s an example:


words = ['banana', 'apple', 'orange', 'pear']
sorted_words = sorted(words, key=lambda word: len(word))
print(sorted_words) # Output: ['pear', 'apple', 'banana', 'orange']

In this example, we pass a lambda function as the key argument that returns the length of each word. This results in a sorted list of words based on their length.

Sorting complex data structures such as lists of dictionaries or tuples can also be achieved using the `sorted()` function with a custom key function. Here’s an example:


students = [
    {'name': 'Alice', 'age': 20},
    {'name': 'Bob', 'age': 19},
    {'name': 'Charlie', 'age': 21}
]

sorted_students = sorted(students, key=lambda student: student['age'])
print(sorted_students)
# Output:
# [{'name': 'Bob', 'age': 19}, {'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 21}]

In this example, we pass a lambda function as the key argument that returns the value of the `’age’` key for each student dictionary. This results in a sorted list of students based on their age.

In summary, the `sorted()` function provides a powerful alternative to the built-in `sort()` function for sorting lists in Python. It can also be used with custom key functions to sort based on specific criteria and can handle complex data structures like lists of dictionaries or tuples.

Conclusion

In conclusion, sorting lists in Python is a common task that can be achieved using the built-in `sort()` function. However, it is important to note that there are alternative ways to sort lists in Python. In this article, we have explored two alternative sorting methods: using the `sorted()` function and using the `heapq` module.

The `sorted()` function returns a new sorted list from an iterable while leaving the original list unchanged. It also accepts a key parameter which can be used to specify a custom sorting order.

On the other hand, the `heapq` module provides functions for implementing heaps based on regular lists. Using the `heappush()` and `heappop()` functions, we can create a sorted list in ascending order.

Overall, understanding these alternative methods of sorting lists in Python can help you write more efficient and flexible code. So next time you need to sort a list, consider trying out these alternatives and see which one works best for your specific use case.
Interested in learning more? Check out our Introduction to Python course!


How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!


Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Data Science, Tutorials

Guide to NLTK – Natural Language Toolkit for Python

Introduction Natural Language Processing (NLP) lies at the heart of countless applications we use every day, from voice assistants to spam filters and machine translation. It allows machines to understand, interpret, and generate human language, bridging the gap between humans and computers. Within the vast landscape of NLP tools and techniques, the Natural Language Toolkit […]

Machine Learning, Tutorials

GridSearchCV with Scikit-Learn and Python

Introduction In the world of machine learning, finding the optimal set of hyperparameters for a model can significantly impact its performance and accuracy. However, searching through all possible combinations manually can be an incredibly time-consuming and error-prone process. This is where GridSearchCV, a powerful tool provided by Scikit-Learn library in Python, comes to the rescue. […]

Python Basics, Tutorials

Plotting Time Series in Python: A Complete Guide

Introduction Time series data is a type of data that is collected over time at regular intervals. It can be used to analyze trends, patterns, and behaviors over time. In order to effectively analyze time series data, it is important to visualize it in a way that is easy to understand. This is where plotting […]