A Complete Guide to Data Structures in Python
Author :: Kevin Vecmanis
This is a post I’ve always wanted to put together - it’s a monster, comprehensive guide to implementing data structures in Python, complete with code, explanations, and use cases.
In this article you will learn about:
- Lists
- Numpy Arrays
- Matrix
- Dictionaries
- Heaps
- Linked Lists
- Queues and Double-ended Queues
- Stacks
- Binary Trees
- Tuples
- Hash Tables
Table of Contents
- Introduction
- Lists
- Numpy Arrays
- Matrix
- Dictionaries
- Heaps
- Linked Lists
- Queues
- Dequeues
- Stacks
- Binary Trees
- Tuples
- Hash Tables
Lists
A list is a collection which is ordered and changeable.
Numpy Arrays
While Python lists offer an efficient solution for the storage of array-based data, a numpy ndarray
offers an efficient to perform operations on array-based data.
Matrix
Dicionaries
Binary Trees
Heaps
There are two types of heaps:
- Min Heap : Each parent node is less than or equal to its child node.
- Max Heap : Each parent node is greater than or equal to its child node.
Heaps are especially useful for implementing priority queues, or any situations where quick access is needed to the maximum or minimum value in a collection.
In python, you can implement a heap using the built in library heapq
. As of this writing, the standard Python implementation of heap is a MinHeap. To get a MaxHeap, you can multiple all the values in the list by -1 and it will perform as a MaxHeap.
Creating the heap
heapify()
Note that althought the smallest element will always be at index 0, the rest of the list isn’t necessarily sorted. That being said, the heapq.heappop()
method will always pop the smallest element (removed the element from the list)
Removing from the heap
heappop()
Adding to the heap
heappush()