Intermediate·Concept·2 min read

Graphs in Python

Practice this question

Graph representation

Python
graph = {
    'A': ['B', 'C'],
    'B': ['D'],
    'C': ['E']
}

Problems to practice

  • Number of Islands
  • Clone Graph
  • Course Schedule
  • Topological Sort
  • BFS and DFS
  • Shortest path in unweighted graph
  • Union-Find problems

Example: BFS

Python
from collections import deque

def bfs(graph, start):
    visited = {start}
    queue = deque([start])

    while queue:
        node = queue.popleft()
        print(node)
        for neighbor in graph.get(node, []):
            if neighbor not in visited:
                visited.add(neighbor)
                queue.append(neighbor)

Adapted from 18_DSA_PYTHON.md · “9. Graphs in Python”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.