• Stars
    star
    3,494
  • Rank 12,739 (Top 0.3 %)
  • Language
    Python
  • License
    Other
  • Created over 10 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python Sorted Container Types: Sorted List, Sorted Dict, and Sorted Set

Python Sorted Containers

Sorted Containers is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions.

Python's standard library is great until you need a sorted collections type. Many will attest that you can get really far without one, but the moment you really need a sorted list, sorted dict, or sorted set, you're faced with a dozen different implementations, most using C-extensions without great documentation and benchmarking.

In Python, we can do better. And we can do it in pure-Python!

>>> from sortedcontainers import SortedList
>>> sl = SortedList(['e', 'a', 'c', 'd', 'b'])
>>> sl
SortedList(['a', 'b', 'c', 'd', 'e'])
>>> sl *= 10_000_000
>>> sl.count('c')
10000000
>>> sl[-3:]
['e', 'e', 'e']
>>> from sortedcontainers import SortedDict
>>> sd = SortedDict({'c': -3, 'a': 1, 'b': 2})
>>> sd
SortedDict({'a': 1, 'b': 2, 'c': -3})
>>> sd.popitem(index=-1)
('c', -3)
>>> from sortedcontainers import SortedSet
>>> ss = SortedSet('abracadabra')
>>> ss
SortedSet(['a', 'b', 'c', 'd', 'r'])
>>> ss.bisect_left('c')
2

All of the operations shown above run in faster than linear time. The above demo also takes nearly a gigabyte of memory to run. When the sorted list is multiplied by ten million, it stores ten million references to each of "a" through "e". Each reference requires eight bytes in the sorted container. That's pretty hard to beat as it's the cost of a pointer to each object. It's also 66% less overhead than a typical binary tree implementation (e.g. Red-Black Tree, AVL-Tree, AA-Tree, Splay-Tree, Treap, etc.) for which every node must also store two pointers to children nodes.

Sorted Containers takes all of the work out of Python sorted collections -making your deployment and use of Python easy. There's no need to install a C compiler or pre-build and distribute custom extensions. Performance is a feature and testing has 100% coverage with unit tests and hours of stress.

Testimonials

Alex Martelli, Fellow of the Python Software Foundation

"Good stuff! ... I like the simple, effective implementation idea of splitting the sorted containers into smaller "fragments" to avoid the O(N) insertion costs."

Jeff Knupp, author of Writing Idiomatic Python and Python Trainer

"That last part, "fast as C-extensions," was difficult to believe. I would need some sort of Performance Comparison to be convinced this is true. The author includes this in the docs. It is."

Kevin Samuel, Python and Django Trainer

I'm quite amazed, not just by the code quality (it's incredibly readable and has more comment than code, wow), but the actual amount of work you put at stuff that is not code: documentation, benchmarking, implementation explanations. Even the git log is clean and the unit tests run out of the box on Python 2 and 3.

Mark Summerfield, a short plea for Python Sorted Collections

Python's "batteries included" standard library seems to have a battery missing. And the argument that "we never had it before" has worn thin. It is time that Python offered a full range of collection classes out of the box, including sorted ones.

Sorted Containers is used in popular open source projects such as: Zipline, an algorithmic trading library from Quantopian; Angr, a binary analysis platform from UC Santa Barbara; Trio, an async I/O library; and Dask Distributed, a distributed computation library supported by Continuum Analytics.

Features

  • Pure-Python
  • Fully documented
  • Benchmark comparison (alternatives, runtimes, load-factors)
  • 100% test coverage
  • Hours of stress testing
  • Performance matters (often faster than C implementations)
  • Compatible API (nearly identical to older blist and bintrees modules)
  • Feature-rich (e.g. get the five largest keys in a sorted dict: d.keys()[-5:])
  • Pragmatic design (e.g. SortedSet is a Python set with a SortedList index)
  • Developed on Python 3.10
  • Tested with CPython 3.7, 3.8, 3.9, 3.10, 3.11, 3.12 and PyPy3
  • Tested on Linux, Mac OSX, and Windows

image

image

Quickstart

Installing Sorted Containers is simple with pip:

$ pip install sortedcontainers

You can access documentation in the interpreter with Python's built-in help function. The help works on modules, classes and methods in Sorted Containers.

>>> import sortedcontainers
>>> help(sortedcontainers)
>>> from sortedcontainers import SortedDict
>>> help(SortedDict)
>>> help(SortedDict.popitem)

Documentation

Complete documentation for Sorted Containers is available at http://www.grantjenks.com/docs/sortedcontainers/

User Guide

The user guide provides an introduction to Sorted Containers and extensive performance comparisons and analysis.

Community Guide

The community guide provides information on the development of Sorted Containers along with support, implementation, and history details.

API Documentation

The API documentation provides information on specific functions, classes, and modules in the Sorted Containers package.

Talks

Resources

Sorted Containers License

Copyright 2014-2024 Grant Jenks

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More Repositories

1

free-python-games

Free Python Games
Python
3,408
star
2

python-diskcache

Python disk-backed cache (Django-compatible). Faster than Redis and Memcached. Pure-Python.
Python
2,331
star
3

blue

The slightly less uncompromising Python code formatter.
Python
389
star
4

python-wordsegment

English word segmentation, written in pure-Python, and based on a trillion-word corpus.
Python
365
star
5

python-pattern-matching

Python pattern matching like functional languages.
Python
162
star
6

py-tree-sitter-languages

Binary Python wheels for all tree sitter languages.
Python
149
star
7

python-sortedcollections

Python Sorted Collections Library
Python
102
star
8

python-runstats

Python module for computing statistics and regression in a single pass.
Python
96
star
9

python-tribool

Python implementation of Tribool data type.
Python
20
star
10

gpt-prompt-notes

GPT Prompt Notes
15
star
11

scikit-sequitur

SciKit Sequitur is an Apache2 licensed Python module for inferring compositional hierarchies from sequences.
Python
9
star
12

largefile

Python large file utilities inspired by GNU Coreutils and functional programming.
Python
7
star
13

django-modelqueue

Task queue based on Django models.
Python
7
star
14

django-replay

Django application that records and replays web requests.
Python
4
star
15

django-rrweb

Django application to record and replay browser sessions.
Python
3
star
16

prioritydict

PriorityDict is an Apache2 licensed implementation of a dictionary which maintains key-value pairs in value sort order.
Python
3
star
17

advent-of-code

Advent of Code https://adventofcode.com/
Python
2
star
18

python-ivenv

Interactive virtual environments for Python.
Python
2
star
19

syntaxforest

Python
2
star
20

django-dblog

Django Database Logs
Python
2
star
21

dotemacs

Emacs Lisp
2
star
22

python-kmp

Python implementation of Knuth-Morris-Pratt algorithm for sequence search.
Python
2
star
23

python-appstore

User-oriented front-end for pip.
Python
2
star
24

python-fount

Python
2
star
25

emacs-starbuck

Emacs Lisp
1
star
26

csvcompare

CSV comparison and diff tools.
Python
1
star
27

python-shims

Shims is an Apache2 licensed Python module with patching and mocking utilities.
Python
1
star
28

python-templates

Python templating library with templates included.
Python
1
star
29

python-qemu-python

C
1
star
30

SynDiff

Syntactic differencing tool.
1
star
31

python-prique

Python
1
star
32

django-codemirror6

Django CodeMirror 6
JavaScript
1
star
33

Sequitur

Sequitur is a program for identifying structure in long sequences.
1
star
34

jupyter-nbconvert-blue

Use "blue" to format Python cells in Jupyter notebooks.
1
star