Python sorted containers | An Introduction
Last Updated :
11 May, 2020
Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. It was created by Grant Jenks and is an open source library. It is a collection of containers that allow us to insert and remove elements very efficiently while maintaining sorted order.
Features:
- Pure-Python
- Fully documented
- Benchmark comparison (alternatives, runtimes, load-factors
- Performance (often faster than C implementations)
- Compatible API (nearly identical to popular blist and rbtree modules)
- Feature-rich (e.g. get the five largest keys in a sorted dict: d.iloc[-5:])
- Pragmatic design (e.g. SortedSet is a Python set with a SortedList index)
Containers:
- SortedList
- SortedDict
- SortedSet
Installation:
Mac and Linux users can install via pip command:
sudo pip install sortedcontainers
SortedList –
Sorted list is a sorted mutable sequence in which the values are maintained in sorted order.
Functions to add and remove elements:
add(value) : A function that takes one element as parameter and inserts it into the list by maintaining sorted order. Runtime Complexity: O(log(n))
update(iterable): A function that takes an iterable as input and updates the SortedList adding all the values from the iterable Runtime complexity: O(k*log(n)).
clear(): Remove all values from sorted list. Runtime complexity: O(n).
discard(value): Remove value from sorted list if it is a member. If value is not a member, do nothing. Runtime complexity: O(log(n)).
Below is the implementation –
from sortedcontainers import SortedList, SortedSet, SortedDict
sorted_list = SortedList([ 1 , 2 , 3 , 4 ])
sorted_list = SortedList()
for i in range ( 5 , 0 , - 1 ):
sorted_list.add(i)
print ( 'list after adding 5 elements: ' , sorted_list)
print ( 'list elements are: ' , end = '')
for i in sorted_list:
print (i, end = ' ' )
print ()
sorted_list.clear()
elements = [ 10 , 9 , 8 , 7 , 6 ]
sorted_list.update(elements)
print ( 'list after updating: ' , sorted_list)
sorted_list.discard( 8 )
print ( 'list after removing one element: ' , sorted_list)
sorted_list.clear()
print ( 'list after removing all elements using clear: ' , sorted_list)
|
Output :
list after adding 5 elements: SortedList([1, 2, 3, 4, 5], load=1000)
list elements are: 1 2 3 4 5
list after updating: SortedList([6, 7, 8, 9, 10], load=1000)
list after removing one element: SortedList([6, 7, 9, 10], load=1000)
list after removing all elements using clear: SortedList([], load=1000)
SortedSet –
Sorted set is a sorted mutable set in which values are unique and maintained in sorted order. Sorted set uses a set for set-operations and maintains a sorted list of values. Sorted set values must be hashable and comparable.
Functions to add and remove elements:
add(value) : A function that takes one element as parameter and inserts it into the set by maintaining sorted order. Runtime Complexity: O(log(n))
clear(): Remove all values from sorted set. Runtime complexity: O(n)
discard(value): Remove value from sorted set if it is a member. If value is not a member, do nothing. Runtime complexity: O(log(n))
from sortedcontainers import SortedList, SortedSet, SortedDict
sorted_set = SortedSet([ 1 , 1 , 2 , 3 , 4 ])
sorted_set = SortedSet()
for i in range ( 5 , 0 , - 1 ):
sorted_set.add(i)
print ( 'set after adding elements: ' , sorted_set)
sorted_set.add( 5 )
print ( 'set after inserting duplicate element: ' , sorted_set)
sorted_set.discard( 4 )
print ( 'set after discarding: ' , sorted_set)
if ( 2 in sorted_set):
print ( '2 is present' )
else :
print ( '2 is not present' )
print ( 'set elements are: ' , end = '')
for i in sorted_set:
print (i, end = ' ' )
print ()
|
Output :
set after adding elements: SortedSet([1, 2, 3, 4, 5], key=None, load=1000)
set after inserting duplicate element: SortedSet([1, 2, 3, 4, 5], key=None, load=1000)
set after discarding: SortedSet([1, 2, 3, 5], key=None, load=1000)
2 is present
set elements are: 1 2 3 5
SortedDict –
Sorted dict is a sorted mutable mapping in which keys are maintained in sorted order. Sorted dict inherits from dict to store items and maintains a sorted list of keys. Sorted dict keys must be hashable and comparable.
Functions to add and remove elements:
setdefault(key, default = None) : Return value for item identified by key in sorted dict. If key is in the sorted dict then return its value. If key is not in the sorted dict then insert key with value default and return default. Runtime Complexity: O(log(n))
clear(): Remove all values from sorted dict. Runtime complexity: O(n)
get(key, default): Return the value for key if key is in the dictionary, else default.
from sortedcontainers import SortedList, SortedSet, SortedDict
sorted_dict = SortedDict({ 'a' : 1 , 'b' : 2 , 'c' : 3 })
sorted_dict = SortedDict({ 'a' : 1 , 'c' : 2 , 'b' : 3 })
print ( 'sorted dict is: ' , sorted_dict)
sorted_dict[ 'd' ] = 3
print ( 'sorted dict after adding an element: ' , sorted_dict)
sorted_dict.setdefault( 'e' , 4 )
print ( 'sorted dict after setdefault(): ' , sorted_dict)
print ( 'using the get function to print the value of a: ' , sorted_dict.get( 'a' , 0 ))
if ( 'a' in sorted_dict):
print ( 'a is present' )
else :
print ( 'a is not present' )
print ( 'dict elements are: ' , end = '')
for key in sorted_dict:
print ( '{} -> {}' . format (key, sorted_dict[key]), end = ' ' )
print ()
sorted_dict.clear()
print ( 'sorted dict after removing all elements: ' , sorted_dict)
|
Output :
sorted dict is: SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2})
sorted dict after adding an element: SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2, 'd': 3})
sorted dict after setdefault(): SortedDict(None, 1000, {'a': 1, 'b': 3, 'c': 2, 'd': 3, 'e': 4})
using the get function to print the value of a: 1
a is present
dict elements are: a -> 1 b -> 3 c -> 2 d -> 3 e -> 4
sorted dict after removing all elements: SortedDict(None, 1000, {})
Reference: http://www.grantjenks.com/docs/sortedcontainers/index.html
Similar Reads
Introduction to Python GIS
Geographic Information Systems (GIS) are powerful tools for managing, analyzing, and visualizing spatial data. Python, a versatile programming language, has emerged as a popular choice for GIS applications due to its extensive libraries and ease of use. This article provides an introduction to Pytho
4 min read
Introduction to Python for Absolute Beginners
Are you a beginner planning to start your career in the competitive world of Programming? Looking resources for Python as an Absolute Beginner? You are at the perfect place. This Python for Beginners page revolves around Step by Step tutorial for learning Python Programming language from very basics
6 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Introduction to JustPy | A Web Framework based on Python
JustPy is a web framework that leverages the power of Python to create web applications effortlessly. In this article, we'll explore JustPy, its features, and why it's gaining attention among developers. What is the JustPy Module of Python?The JustPy module of Python is a web framework like Django b
8 min read
Inbuilt Data Structures in Python
Python has four non-primitive inbuilt data structures namely Lists, Dictionary, Tuple and Set. These almost cover 80% of the our real world data structures. This article will cover the above mentioned topics. Above mentioned topics are divided into four sections below. Lists: Lists in Python are one
3 min read
10 Interesting Python Code Tricks
In python we can return multiple values - It's very unique feature of Python that returns multiple value at time. [GFGTABS] Python def GFG(): g = 1 f = 2 return g, f x, y = GFG() print(x, y) [/GFGTABS]Output(1, 2) Allows Negative Indexing: Python allows negative indexing for its sequences. Index -1
2 min read
Creating Your Own Python IDE in Python
In this article, we are able to embark on an adventure to create your personal Python Integrated Development Environment (IDE) the usage of Python itself, with the assistance of the PyQt library. What is Python IDE?Python IDEs provide a characteristic-rich environment for coding, debugging, and goin
3 min read
Understanding Code Reuse and Modularity in Python 3
What is Object Oriented Programming(OOP)? OOP is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. Learn more here, or just Google "OOP".Objects have charact
7 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 Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read