DSA: The 8-Week Grind — Day 4

SAI GOUTHAMSAI GOUTHAM
4 min read

Python’s Core Data Structures — Choose the Right Tool

“DSA is easy… when you know where your data lives.”


🟡 Why Learn Data Structures First?

Most people fail at DSA not because they can’t write code — but because they’re using the wrong structure.
Today, I’m diving into 9 core Python data structures that you must know to write clean, efficient solutions.


🔹 1. List — Python’s Built-in Dynamic Array

What it is:
An ordered collection that can grow/shrink, supports indexing, slicing, iteration.

When to use:

  • When you need to store ordered items

  • When index-based access is required

  • Great for implementing stacks/queues manually

fruits = ['apple', 'banana', 'cherry']
fruits.append('mango')
print(fruits[1])  # Output: banana
print(fruits)     # Output: ['apple', 'banana', 'cherry', 'mango']

🔹 2. Tuple — Immutable List

What it is:
A fixed-size, ordered collection — can’t be modified after creation.

When to use:

  • When you want to protect the data from being changed

  • Useful for coordinates, return values, or as dictionary keys

point = (10, 20)
print(point[0])  # Output: 10
# point[0] = 30 ❌ Error: Tuples are immutable

🔹 3. Set — Unordered Unique Collection

What it is:
Stores only unique items and allows fast membership tests.

When to use:

  • When you need to eliminate duplicates

  • When you need fast lookup (O(1) on average)

  • For intersection, union, difference operations

nums = {1, 2, 3, 3, 2}
nums.add(4)
print(nums)       # Output: {1, 2, 3, 4}
print(2 in nums)  # Output: True

🔹 4. Dict — Key-Value Store (Hash Table)

What it is:
A mapping between unique keys and values.

When to use:

  • When you want to store relationships (like name ➝ age)

  • When you need fast lookups by key

  • When building frequency maps, caches, graphs

student = {"name": "Goutham", "age": 24}
student["grade"] = "A"
print(student["name"])  # Output: Goutham
print(student)          # Output: {'name': 'Goutham', 'age': 24, 'grade': 'A'}

🔹 5. Stack — Last In First Out (LIFO)

What it is:
A structure where the last element added is the first one removed.

When to use:

  • Backtracking problems

  • Undo functionality

  • Balanced parentheses, DFS, reversing operations

stack = []
stack.append(1)
stack.append(2)
stack.pop()        # Output: 2
print(stack)       # Output: [1]

🔹 6. Queue — First In First Out (FIFO)

What it is:
A structure where the first item added is the first removed.

When to use:

  • Task scheduling

  • BFS traversal in trees/graphs

  • Producer-consumer problems

from collections import deque

queue = deque()
queue.append(1)
queue.append(2)
queue.popleft()     # Output: 1
print(queue)        # Output: deque([2])

🔹 7. Heap — Priority Queue (Min-Heap)

What it is:
A binary heap where the smallest element is always on top.

When to use:

  • When you need top K smallest/largest

  • For scheduling, Dijkstra’s shortest path, median in stream

import heapq

nums = [5, 1, 3]
heapq.heapify(nums)
heapq.heappush(nums, 2)
print(heapq.heappop(nums))  # Output: 1
print(nums)                 # Output: [2, 5, 3]

🔹 8. DefaultDict — Auto-Creates Default Values

What it is:
A dictionary that doesn’t crash when accessing non-existent keys.

When to use:

  • For counting frequencies

  • Grouping elements (like anagrams)

  • Avoiding KeyError in nested logic

from collections import defaultdict

freq = defaultdict(int)
freq['a'] += 1
print(freq['a'])  # Output: 1
print(freq['b'])  # Output: 0

🔹 9. Counter — Frequency Counter in One Line

What it is:
A subclass of dict for counting hashable objects.

When to use:

  • Counting elements (like characters, words)

  • When you want to avoid writing manual counting logic

from collections import Counter

arr = [1, 2, 2, 3, 3, 3]
count = Counter(arr)
print(count)     # Output: Counter({3: 3, 2: 2, 1: 1})
print(count[2])  # Output: 2

Day 4 Takeaways:

  • Lists = go-to for ordered data

  • Dicts = best for fast key-value lookups

  • Sets = uniqueness + fast membership

  • Stacks & Queues = control order of processing

  • Heaps = when priority matters

  • Counter & DefaultDict = frequency problems = solved
    Now you know not just what they are, but when to use each one.


0
Subscribe to my newsletter

Read articles from SAI GOUTHAM directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

SAI GOUTHAM
SAI GOUTHAM

💻 Experienced Computer Science graduate with 3+ years in software engineering, specializing in full-stack web development and cloud solutions. 🥇 Proficient in Python, JavaScript, and SQL, with expertise in React.js, Node.js, Django, and Flask. 🎖️ Skilled in optimizing system performance and deploying scalable applications using AWS. Strong background in agile methodologies and DevOps practices. 🥅 Committed to delivering high-quality, efficient, and scalable software solutions.