All the books I’ve read on data structures so far seem to use C/C++, and make heavy use of the “manual” pointer control that they offer. Since Python hides that sort of memory management and garbage collection from the user is it even possible to implement efficient data structures in this language, and is there any reason to do so instead of using the built-ins?
Share
Python gives you some powerful, highly optimized data structures, both as built-ins and as part of a few modules in the standard library (
lists anddicts, of course, but alsotuples,sets,arrays in module array, and some other containers in module collections).Combinations of these data structures (and maybe some of the functions from helper modules such as heapq and bisect) are generally sufficient to implement most richer structures that may be needed in real-life programming; however, that’s not invariably the case.
When you need something more than the rich library provides, consider the fact that an object’s attributes (and items in collections) are essentially “pointers” to other objects (without pointer arithmetic), i.e., “reseatable references”, in Python just like in Java. In Python, you normally use a
Nonevalue in an attribute or item to represent whatNULLwould mean in C++ ornullwould mean in Java.So, for example, you could implement binary trees via, e.g.:
plus methods or functions for traversal and similar operations (the
__slots__class attribute is optional — mostly a memory optimization, to avoid eachNodeinstance carrying its own__dict__, which would be substantially larger than the three needed attributes/references).Other examples of data structures that may best be represented by dedicated Python classes, rather than by direct composition of other existing Python structures, include
tries(see e.g. here) andgraphs(see e.g. here).