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
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
Formatting containers using format() in Python Let us see how to format containers that were accessed through __getitem__ or getattr() using the format() method in Python. Accessing containers that support __getitem__a) For Dictionaries Python3 # creating a dictionary founder = {'Apple': 'Steve Jobs', 'Microsoft': 'Bill Gates'} # formatting prin
1 min read
Python Crash Course If you are aware of programming languages and ready to unlock the power of Python, enter the world of programming with this free Python crash course. This crash course on Python is designed for beginners to master Python's fundamentals in record time! Experienced Python developers developed this fre
7 min read