Comprehensive Guide to Data Structures
in Python
Name, Explanation, Real Life Example, and Python Code Example
Introduction
Data structures are fundamental building blocks in programming, providing efficient
ways to store, organize, and manipulate data. In Python, a variety of data structures are
available, each serving specific purposes and use cases. Understanding these
structures is crucial for writing clean, efficient, and maintainable code.
This document presents the most common data structures in Python. For each, you will
find:
• Name
• 2. Explanation
• 3. Real Life Example
• 4. Python Code Example (code-friendly format)
1. List
1. Name: List
2. Explanation:
A list is an ordered, mutable (changeable) collection of items. Lists can contain
elements of different data types and allow duplicate values.
3. Real Life Example:
A shopping list where you can add, remove, or modify items as needed.
4. Python Code Example:
# Creating a list
shopping_list = ["milk", "eggs", "bread"]
# Adding an item
shopping_list.append("butter")
# Removing an item
shopping_list.remove("eggs")
# Accessing elements
print(shopping_list[0]) # Output: milk
2. Tuple
1. Name: Tuple
2. Explanation:
A tuple is an ordered, immutable (unchangeable) collection of items. Once created, the
values inside a tuple cannot be altered.
3. Real Life Example:
Storing the latitude and longitude coordinates of a location.
4. Python Code Example:
# Creating a tuple
coordinates = (52.3702, 4.8952)
# Accessing tuple elements
latitude = coordinates[0]
longitude = coordinates[1]
3. Dictionary
1. Name: Dictionary
2. Explanation:
A dictionary is an unordered collection of key-value pairs. Keys must be unique and
immutable, while values can be of any type.
3. Real Life Example:
A phone book mapping names to phone numbers.
4. Python Code Example:
# Creating a dictionary
phone_book = {"Alice": "123-4567", "Bob": "987-6543"}
# Adding a new entry
phone_book["Charlie"] = "555-1234"
# Accessing a value by key
print(phone_book["Alice"])
4. Set
1. Name: Set
2. Explanation:
A set is an unordered collection of unique elements. Sets do not allow duplicate items
and are commonly used for membership testing and removing duplicates.
3. Real Life Example:
A collection of unique email addresses in a mailing list.
4. Python Code Example:
# Creating a set
# Adding an email
emails.add("[email protected]")
# Removing duplicates from a list using set
5. String
1. Name: String
2. Explanation:
A string is a sequence of characters. Strings are immutable, meaning their contents
cannot be altered after creation.
3. Real Life Example:
A person's full name.
4. Python Code Example:
# Creating a string
name = "John Doe"
# Accessing characters
first_letter = name[0]
# Concatenation
greeting = "Hello, " + name
6. Stack
1. Name: Stack
2. Explanation:
A stack is a collection that follows the Last-In-First-Out (LIFO) principle. Elements are
added and removed from the top of the stack.
3. Real Life Example:
A stack of plates where the last plate placed on top is the first one to be removed.
4. Python Code Example:
# Using a list as a stack
stack = []
# Pushing items onto the stack
stack.append('plate1')
stack.append('plate2')
# Popping item from the stack
top_plate = stack.pop()
7. Queue
1. Name: Queue
2. Explanation:
A queue is a collection that follows the First-In-First-Out (FIFO) principle. Items are
added at the end and removed from the front.
3. Real Life Example:
A line of customers waiting at a ticket counter.
4. Python Code Example:
from collections import deque
# Creating a queue
queue = deque()
# Enqueue
queue.append('customer1')
queue.append('customer2')
# Dequeue
first_customer = queue.popleft()
8. Deque
1. Name: Deque
2. Explanation:
A deque (double-ended queue) allows elements to be added or removed from both
ends efficiently.
3. Real Life Example:
A line of people where someone can join or leave from either end.
4. Python Code Example:
from collections import deque
d = deque([1, 2, 3])
d.appendleft(0) # Add to front
d.append(4) # Add to end
d.pop() # Remove from end
d.popleft() # Remove from front
9. Priority Queue
1. Name: Priority Queue
2. Explanation:
In a priority queue, elements are served based on their priority rather than the order of
insertion.
3. Real Life Example:
A hospital emergency room where patients with higher severity are treated first.
4. Python Code Example:
import heapq
pq = []
heapq.heappush(pq, (2, "patient2"))
heapq.heappush(pq, (1, "patient1")) # Lower number = higher priority
# Popping the highest priority patient
priority, patient = heapq.heappop(pq)
10. Linked List
1. Name: Linked List
2. Explanation:
A linked list is a linear collection of nodes where each node points to the next. It allows
efficient insertion and removal of elements from any position.
3. Real Life Example:
A chain of train cars linked together.
4. Python Code Example:
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Creating a linked list: 1 -> 2 -> 3
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
11. Hash Table
1. Name: Hash Table
2. Explanation:
A hash table stores key-value pairs and uses a hash function to compute an index into
an array of buckets.
3. Real Life Example:
A dictionary where you look up the meaning of a word.
4. Python Code Example:
# Python's built-in dict is a hash table
hash_table = {}
hash_table["apple"] = "A fruit"
hash_table["car"] = "A vehicle"
# Access the value
print(hash_table["apple"])
12. Binary Tree
1. Name: Binary Tree
2. Explanation:
A tree data structure in which each node has at most two children, referred to as left
child and right child.
3. Real Life Example:
A family tree where each person has at most two direct descendants.
4. Python Code Example:
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Creating a simple binary tree
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
13. Graph
1. Name: Graph
2. Explanation:
A graph is a collection of nodes (vertices) and edges connecting pairs of nodes. It can be
directed or undirected.
3. Real Life Example:
A social network where people are nodes and friendships are edges.
4. Python Code Example:
# Using a dictionary to represent an adjacency list
graph = {
"Alice": ["Bob", "Charlie"],
"Bob": ["Alice", "Diana"],
"Charlie": ["Alice"],
"Diana": ["Bob"]
14. Heap
1. Name: Heap
2. Explanation:
A heap is a specialized tree-based structure that satisfies the heap property; in a max
heap, each parent node is greater than or equal to its children.
3. Real Life Example:
A priority queue for job scheduling.
4. Python Code Example:
import heapq
# Create a min-heap
heap = [21, 1, 45, 78, 3, 5]
heapq.heapify(heap)
# Push a new element
heapq.heappush(heap, 8)
# Pop the smallest element
smallest = heapq.heappop(heap)
15. Array
1. Name: Array
2. Explanation:
An array is a data structure that stores a fixed-size sequence of elements of the same
type. In Python, the built-in list is often used, but the array module or numpy arrays
provide more efficient storage for large collections of numbers.
3. Real Life Example:
A row of lockers, each holding a number.
4. Python Code Example:
import array
# Creating an array of integers
numbers = array.array('i', [1, 2, 3, 4, 5])
# Access an element
print(numbers[2]) # Output: 3
Conclusion
Each data structure has its strengths and is suited to particular types of tasks and
problems. Mastering these structures is essential for effective problem solving and
software development in Python. As you continue your coding journey, refer back to
these examples for guidance and inspiration.