post cover

Data Structures in Python, A Thrilling Guide for All Developers

Data Structures in Python, A Thrilling Guide for All Developers

Let’s face it, data structures can be boring. But not in Python! This dynamic language provides a plethora of built-in and user-defined data structures that can make your coding journey not just efficient, but also super exciting.

Built-in data structures: Ready, Set, Go

Python comes loaded with some fantastic data structures that can be used right out of the box.

Lists

The Swiss Army Knife of Data Structures. Lists are versatile, ordered, and mutable. Whether you need to keep track of grocery items or store your favorite movies, lists have got you covered.

# Create a list
my_list = [1, 2, 3, 4, 5]

# Create a list of mixed data types

my_list = [1, "Hello", 3.4]

# Nested list

my_list = ["mouse", [8, 4, 6], ['a']]

Time complexity for list:

Methods Big-O Efficiency
insert O(1)
delete O(n)
slicing O(n)
retrieve O(n)
copy O(n)

Tuples

Unbreakable, Yet Flexible. Tuples may be immutable, but they still pack a punch. Use them as keys in dictionaries or as elements in sets. They’re the perfect solution when you need to keep data safe but accessible.

# Create a tuple
my_tuple = (1, 2, 3, 4, 5)

# Create a tuple of mixed data types

my_tuple = (1, "Hello", 3.4)

# Nested tuple

my_tuple = ("mouse", [8, 4, 6], ('a'))

Time complexity for tuple:

Function Big-O Efficiency
append O(1)

Sets

No More Duplicates, Ever! Sets are the heroes of the data structure world, zapping duplicates in no time. They’re unordered, but who cares when they can handle repetitive data like a pro?

# Create a set
my_set = {1, 2, 3, 4, 5}

# Create a set of mixed data types

my_set = {1, "Hello", 3.4}

# Nested set

my_set = {"mouse", [8, 4, 6], {'a'}}

Time complexity for set:

Operation Big-O Efficiency
Add O(1)
Remove O(1)
Copy O(n)
Update O(n)

Dictionary

The Power of Key-Value Pairs. Dictionaries are the perfect representation for complex data structures. With their speedy implementation, you’ll never struggle to access the values you need.

# Create a dictionary

my_dict = {'name': 'John', 'age': 26}

# Create a dictionary with mixed keys

my_dict = {'name': 'John', 1: [2, 4, 3]}

# Create a nested dictionary

my_dict = {'name': 'John', 1: {'a': 'A', 'b': 'B'}}

Time complexity for dictionary:

Operation Big-O Efficiency
Get O(1)
Set O(1)
Copy O(n)
Update O(n)

User-defined data structures: The Sky’s the Limit

Python doesn’t just stop at the built-in data structures. Developers can also create their own masterpieces with user-defined data structures.

Stacks

Last In, First Out? More like YES! Stacks are a linear data structure that embody the LIFO principle. Use them to evaluate expressions or keep track of function calls. There are a few options to implement a Stack:

  1. Using a list
  2. Using a deque
  3. Using a queue.LifoQueue

# Create a stack using a list

stack = []

# Add items to the stack

stack.append(1)
stack.append(2)

# Remove items from the stack

stack.pop()
stack.pop()

# Get the last item from the stack

stack[-1]

# Create a stack using a deque

from collections import deque

stack = deque()

# Add items to the stack

stack.append(1)
stack.append(2)

# Remove items from the stack

stack.pop()

# Get the last item from the stack

stack[-1]

# Create a stack using a queue.LifoQueue

from queue import LifoQueue

stack = LifoQueue(maxsize = 3)

# Add items to the stack

stack.put(1)
stack.put(2)

# Remove items from the stack

stack.get()

# Get the last item from the stack

stack.queue[-1]

The difference between deque and LifoQueue:

  1. LifoQueue is thread safe, while deque is not.
  2. LifoQueue has a maxsize, while deque does not.
  3. LifoQueue has a task_done method, while deque does not.
  4. LifoQueue has a join method, while deque does not.

Time complexity for stack:

Operation Big-O Efficiency
Push O(1)
Pop O(1)
Peek O(1)
Size O(1)

Queues

First In, First Out? Absolutely! Queues are the embodiment of the FIFO principle. Schedule your tasks with ease, or maintain a sequence of events like a boss.

from collections import deque

# Create a queue
queue = deque()

# Add items to the queue
queue.append(1)
queue.append(2)


# Remove items from the queue
queue.popleft()

# Get the first item from the queue

queue[0]

Tree

The Hierarchical Hero. Trees are data structures that provide parent-child relationships. Organize your data and search with ease, because with trees, the sky’s the limit.

Types of trees

  • Binary tree
  • Full tree
  • Perfect tree
  • Ordered tree

Graph

Connect the Dots. Graphs are collections of vertices connected by edges. They’re the perfect tool for representing complex relationships and finding the shortest paths.

Linked list

Chain Reaction. Linked lists are linear data structures where each node contains a value and a pointer to the next node. They’re the perfect solution for efficient insertion and deletion of elements.


class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

    def __repr__(self):
        return self.data

class LinkedList:
    def __init__(self):
        self.head = None

    def __repr__(self):
        node = self.head
        nodes = []
        while node is not None:
            nodes.append(node.data)
            node = node.next
        nodes.append("None")
        return " -> ".join(nodes)

HashMap or HashTable

Hash it Out. HashMaps and HashTables map keys to values using a hash function. They’re the perfect representation for dictionaries and sets.


# Create a hash map
hash_map = {}

# Add items to the hash map

hash_map['name'] = 'John'
hash_map['age'] = 26

# Remove items from the hash map

del hash_map['age']

# Get the value of a key

hash_map['name']

A Hash function turns any data into a fixed-size sequence of bytes. There are a few functions available:

  1. md5
  2. sha1
  3. sha224
  4. sha256
  5. sha384
  6. sha512

import hashlib

# Create a hash function

hash_object = hashlib.md5(b'Hello World')

# Get the hex representation of the hash

hash_object.hexdigest()

Heap

The Priority Player. Heaps are binary trees that maintain the heap property. Use them to implement priority queues and get the job done in no time.

import heapq

# Create a heap
heap = []

# Use heapify() function to turn heap from least to heap
heapq.heapify(heap)

# Add items to the heap

heapq.heappush(heap, 1)
heapq.heappush(heap, 2)

# Remove items from the heap

heapq.heappop(heap)

# Get the first item from the heap

heap[0]

Data frames

Data, Meet Python. Data frames are two-dimensional data structures that can be used for data manipulation and analysis. They’re the perfect tool for data science and machine learning.

# Create a data frame
import pandas as pd

df = pd.DataFrame({'name': ['John', 'Steve', 'Sarah'], 'age': [26, 24, 22]})

Matrix

The Power of Numbers. Matrices are two-dimensional arrays of numbers. They’re widely used in linear algebra and computer graphics, and they pack a punch.

# Create a matrix
import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

Vector

One-Dimensional Dynamite. Vectors are one-dimensional arrays of numbers. They’re widely used in linear algebra and computer graphics, and they’re a force to be reckoned with.

# Create a vector
import numpy as np

vector = np.array([1, 2, 3])

Conclusion: Ready to Rock the Data Structure World?

In conclusion, Python offers a wide range of built-in and user-defined data structures that are sure to make your coding journey an exciting.