What are Data Structures?
A data structure is a way of organizing data so that it can be used efficiently. Just like you keep your
clothes in a cupboard (shirts in one shelf, pants in another), a computer also needs to store data in an
organized way.
Basic Types of Data Structures (Built-in in Python)
Data Structure Example in Python
List marks = [80, 90, 100]
Tuple student = ('John', 15)
Set colors = {'red', 'blue', 'green'}
Dictionary person = {'name': 'John', 'age': 15}
Now let’s learn the advanced data structures :
1. Linked List
➤ What is it?
A Linked List is like a chain of boxes. Each box stores data and a link (pointer) to the next box.
➤ Real Life Example:
A train where each bogie is connected to the next.
➤ Visual:
[10 | next] → [20 | next] → [30 | None]
➤ Python Example:
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Creating nodes
node1 = Node(10)
node2 = Node(20)
node3 = Node(30)
# Linking nodes
node1.next = node2
node2.next = node3
# Traversing the list
current = node1
while current:
print(current.data)
current = current.next
2. Stack
➤ What is it?
A Stack is like a pile of plates. You can only add or remove from the top.
➤ Rule:
LIFO – Last In First Out
➤ Python Example:
python
CopyEdit
stack = []
stack.append(10)
stack.append(20)
stack.append(30)
print(stack.pop()) # Removes 30
print(stack) # [10, 20]
3. Queue
➤ What is it?
A Queue is like a line of people waiting for a ticket. The first person goes first.
➤ Rule:
FIFO – First In First Out
➤ Python Example:
from collections import deque
queue = deque()
queue.append(10)
queue.append(20)
queue.append(30)
print(queue.popleft()) # Removes 10
print(queue) # deque([20, 30])
4. Trees
➤ What is it?
A Tree is a structure like a family tree. One element is the root, and it can have branches called children.
➤ Real Life Example:
A folder system in a computer.
➤ Simple Tree Example:
markdown
CopyEdit
10
/ \
20 30
➤ Python Code:
python
CopyEdit
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
root = TreeNode(10)
root.left = TreeNode(20)
root.right = TreeNode(30)
print(root.left.value) # 20
5. Graphs
➤ What is it?
A Graph is a set of points (nodes) connected by lines (edges). Unlike trees, it can have loops and cycles.
➤ Real Life Example:
Google Maps (locations connected by roads).
➤ Types:
• Undirected Graph: A-B is same as B-A
• Directed Graph: A → B is different from B → A
➤ Python Example using Dictionary:
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['E'],
'D': [],
'E': []
}
# Printing connections
for node in graph:
print(f"{node} is connected to {graph[node]}")
Summary Table
Data Structure Concept Real Life Example
Linked List Chain of nodes Train
Stack LIFO Plates stack
Queue FIFO People in a line
Tree Hierarchical Folder structure
Graph Network of nodes Roads between cities