Python sorted containers - An Introduction

Python offers a wide range of data structures to efficiently organize and manipulate data. When it comes to handling sorted data, sorted containers play a crucial role. Sorted containers are data structures that maintain elements in a sorted order, providing fast access, insertion, and deletion operations.

In this article, we will explore Python sorted containers and understand their significance in various applications. We will examine the different types of sorted containers and discuss their features, advantages, and implementation details.

What are Sorted Containers?

Sorted containers are specialized data structures that automatically maintain their elements in sorted order. Unlike regular Python lists or sets, sorted containers keep elements organized as you add or remove them, eliminating the need for manual sorting.

Installation

Sorted containers are not part of Python's standard library. Install the sortedcontainers package ?

pip install sortedcontainers

Types of Sorted Containers

Python provides three main types of sorted containers ?

SortedList

A SortedList maintains elements in sorted order and supports fast insertion, deletion, and indexing operations ?

from sortedcontainers import SortedList

# Create a sorted list
sl = SortedList([3, 1, 4, 1, 5])
print("Initial list:", sl)

# Add elements
sl.add(2)
sl.add(6)
print("After adding 2 and 6:", sl)

# Remove element
sl.remove(1)
print("After removing first 1:", sl)

# Access by index
print("Element at index 2:", sl[2])
Initial list: SortedList([1, 1, 3, 4, 5])
After adding 2 and 6: SortedList([1, 1, 2, 3, 4, 5, 6])
After removing first 1: SortedList([1, 2, 3, 4, 5, 6])
Element at index 2: 3

SortedSet

A SortedSet is a collection of unique elements maintained in sorted order ?

from sortedcontainers import SortedSet

# Create a sorted set
ss = SortedSet([3, 1, 4, 1, 5])
print("Initial set:", ss)

# Add elements
ss.add(2)
ss.add(1)  # Duplicate, won't be added
print("After adding 2 and 1:", ss)

# Check membership
print("Is 3 in set?", 3 in ss)

# Get range
print("Elements from 2 to 4:", ss[ss.bisect_left(2):ss.bisect_right(4)])
Initial set: SortedSet([1, 3, 4, 5])
After adding 2 and 1: SortedSet([1, 2, 3, 4, 5])
Is 3 in set? True
Elements from 2 to 4: [2, 3, 4]

SortedDict

A SortedDict is a dictionary where keys are maintained in sorted order ?

from sortedcontainers import SortedDict

# Create a sorted dictionary
sd = SortedDict({'c': 3, 'a': 1, 'b': 2})
print("Initial dict:", dict(sd))

# Add key-value pairs
sd['d'] = 4
sd['a'] = 10  # Update existing key
print("After updates:", dict(sd))

# Access keys in sorted order
print("Keys:", list(sd.keys()))
print("Values:", list(sd.values()))

# Get items in range
print("Keys from 'b' to 'd':", list(sd.irange('b', 'd')))
Initial dict: {'a': 1, 'b': 2, 'c': 3}
After updates: {'a': 10, 'b': 2, 'c': 3, 'd': 4}
Keys: ['a', 'b', 'c', 'd']
Values: [10, 2, 3, 4]
Keys from 'b' to 'd': ['b', 'c', 'd']

Key Features

Underlying Data Structure

Sorted containers use a hybrid approach combining balanced binary search trees and sorted lists. This design provides O(log n) complexity for most operations while maintaining cache efficiency.

Time Complexity

Operation Time Complexity Description
Insertion O(log n) Add element maintaining order
Deletion O(log n) Remove element
Search O(log n) Find element
Indexing O(log n) Access by position
Range Query O(log n + k) k = elements in range

Practical Example

Here's a practical example using sorted containers to maintain a leaderboard ?

from sortedcontainers import SortedDict

class Leaderboard:
    def __init__(self):
        self.scores = SortedDict()
    
    def add_score(self, player, score):
        self.scores[score] = player
    
    def get_top_players(self, n=3):
        # Get top n players (highest scores)
        top_scores = list(self.scores.keys())[-n:]
        return [(self.scores[score], score) for score in reversed(top_scores)]

# Create leaderboard
board = Leaderboard()
board.add_score("Alice", 95)
board.add_score("Bob", 87)
board.add_score("Charlie", 92)
board.add_score("Diana", 98)

print("Top 3 players:")
for player, score in board.get_top_players(3):
    print(f"{player}: {score}")
Top 3 players:
Diana: 98
Alice: 95
Charlie: 92

Advantages Over Standard Containers

  • Automatic Sorting No need to manually sort after modifications

  • Efficient Operations O(log n) for insertion, deletion, and search

  • Range Queries Fast retrieval of elements within a range

  • Memory Efficient Optimized internal structure reduces overhead

Conclusion

Sorted containers provide an elegant solution for maintaining data in sorted order with efficient operations. They offer better performance than manually sorting standard containers and include specialized methods for range queries and ordered access. Consider using sorted containers when your application requires frequently updated sorted data.

Updated on: 2026-03-27T12:13:42+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements