Sorted Containers is a powerful Python library that provides fast and easy-to-use implementations of SortedList, SortedDict and SortedSet data types. Unlike Python’s built-in types, these containers maintain their elements in sorted order automatically as elements are added or removed. To use this library, you need to install it using the following command:
pip install sortedcontainers
Why use sorted containers?
Let's understand the use cases of Sorted Containers.
- Automatic Sorting: Keeps your data sorted automatically without needing to call sort() every time you update it.
- Fast and Efficient: Written in Python but optimized for speed, often matching C-based libraries.
- Easy to Use: Works just like Python's list, dict and set, so it's easy to learn and use.
- Memory Efficient: Uses advanced structures like B-trees to balance speed and memory usage effectively.
Key components of sorted containers
Let’s understand the key components of the sortedcontainers library, which automatically maintain sorted order while offering efficient and intuitive operations.
1. SortedList: It is a special type of list from the sortedcontainers module. It automatically maintains the order of its elements, meaning that each time you add or remove an element, the list remains sorted. Its key functions include:
- add(value) inserts the value while maintaining order.
- update(iterable) adds all values from an iterable, maintaining order.
- clear() removes all elements.
- discard(value) removes the value if it exists.
Python
from sortedcontainers import SortedList
a = SortedList([1, 2, 3, 4, 5])
print(a)
a.add(6)
print(a)
a.clear()
print(a)
Output
SortedList([1, 2, 3, 4, 5])
SortedList([1, 2, 3, 4, 5, 6])
SortedList([])
Explanation:
- SortedList([1, 2, 3, 4, 5]) initializes a sorted list and a.add(6) inserts 6 while maintaining the sorted order.
- a.clear() removes all elements from the list, making it an empty SortedList([]).
2. SortedSet: It is a mutable set that maintains unique elements in sorted order. It combines set operations with sorting. It's key functions include:
- add(value) adds a value while maintaining order.
- clear() removes all elements.
- discard(value) removes the value if it exists.
Python
from sortedcontainers import SortedSet
a = SortedSet([1, 2, 3, 4, 5])
print(a)
a.add(6)
print(a)
a.discard(3)
print(a)
Output
SortedSet([1, 2, 3, 4, 5])
SortedSet([1, 2, 3, 4, 5, 6])
SortedSet([1, 2, 4, 5, 6])
Explanation:
- SortedSet([1, 2, 3, 4, 5]) initializes a sorted set with unique elements and a.add(6) inserts 6 while maintaining the sorted order.
- a.discard() removes the value 3 from the set if it exists.
3.SortedDict: It is a mutable mapping that maintains keys in sorted order. It combines dictionary functionality with sorting. It's key functions include:
- setdefault(key, default) returns the value for the key, inserting the key with a default if not found.
- clear() removes all key-value pairs.
- get(key, default) retrieves the value for the key or the default if not present.
Python
from sortedcontainers import SortedDict
d = SortedDict({3: 'c', 1: 'a', 2: 'b'})
print(d)
d[0] = 'z'
print(d)
val = d.setdefault(4, 'd')
print(d)
print(val)
miss = d.get(5, 'default_value')
print(miss)
d.clear()
print(d)
Output
SortedDict({1: 'a', 2: 'b', 3: 'c'})
SortedDict({0: 'z', 1: 'a', 2: 'b', 3: 'c'})
SortedDict({0: 'z', 1: 'a', 2: 'b', 3: 'c', 4: 'd'})
d
default_value
SortedDict({})
Explanation:
- SortedDict({3: 'c', 1: 'a', 2: 'b'}) initializes a dictionary and automatically sorts keys.
- a[0] = 'z' adds a new key-value pair, the dictionary is re-sorted as {0, 1, 2, 3}.
- a.setdefault(4, 'd') checks if key 4 exists if not, adds it with value 'd'.
- a.get(5, 'default_value') tries to get value for key 5 and returns the default since 5 doesn't exist.
- a.clear() removes all items from the dictionary.
Similar Reads
Python sorted containers | An Introduction
Sorted Containers is a powerful Python library that provides fast and easy-to-use implementations of SortedList, SortedDict and SortedSet data types. Unlike Pythonâs built-in types, these containers maintain their elements in sorted order automatically as elements are added or removed. To use this l
3 min read
Conda vs Poetry in Python
When it comes to managing Python environments and dependencies, two tools often stand out: Conda and Poetry. Each has its strengths and specific use cases, catering to different needs within the Python development community. This article explores the key features, advantages, and differences between
4 min read
Collections.UserList in Python
Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
2 min read
Stack in Python
A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop. The functions associated wi
8 min read
Python Virtual Machine
The Python Virtual Machine (VM) is a crucial component of the Python runtime environment. It executes Python bytecode, which is generated from Python source code or intermediate representations like Abstract Syntax Trees (ASTs). In this article, we'll explore the Python Virtual Machine, discussing i
3 min read
Python Data Structures
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as comp
15+ min read
Python vs Cpython
Python is a high-level, interpreted programming language favored for its readability and versatility. It's widely used in web development, data science, machine learning, scripting, and more. However, Cpython is the default and most widely used implementation of the Python language. It's written in
4 min read
Python Docstrings
When it comes to writing clean, well-documented code, Python developers have a secret weapon at their disposal â docstrings. Docstrings, short for documentation strings, are vital in conveying the purpose and functionality of Python functions, modules, and classes.What are the docstrings in Python?P
10 min read
What is a Python wheel?
Python wheels are a pre-built binary package format for Python modules and libraries. They are designed to make it easier to install and manage Python packages, by providing a convenient, single-file format that can be downloaded and installed without the need to compile the package from source code
6 min read
Conftest in pytest
The testing framework in Python that is used to write various types of software tests, including unit tests, integration tests, etc is called Pytest. The Pytest gives the user the ability to use the common input in various Python files, this is possible using Conftest. The conftest.py is the Python
2 min read