Member-only story
Stop Manually Sorting Your List In Python If Performance Is Concerned
A sorted collection library that is as fast as C-extensions
At least for myself, most of the time when I code using Python, I am dealing with collection types. That includes the native Python List, Set, and Dictionary, as well as some third-party collection types such as Numpy Array and Tensorflow tensors. The latter are usually much faster because they are implemented using CPython or whatever C-related extensions.
However, sometimes it is too overwhelming to use them. Especially when we are developing an application that is irrelevant to Data Science, these libraries might be bulky to be involved just for better performance.
In this article, I’ll introduce a library called Sorted Containers, which provides the best practice when a sorted collection type is needed. I’ll cover the two major types from this library: Sorted List and Sorted Set. I will give some real-world examples to make it easier to understand.
Before everything, make sure you’ve installed the library using pip
.
pip install sortedcontainers