
Python’s power lies in its simplicity—and much of that comes from its data structures. Whether you’re building web apps, analyzing data, or solving algorithmic challenges, the right structure helps you write faster, cleaner, and more efficient code.
In this post, we’ll cover all the major Python data structures—from built-ins to advanced modules.
1. Lists – The Go-To Sequence
- Ordered, mutable, allows duplicates
- Great for dynamic collections like tasks, records, or datasets
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")
fruits[1] = "orange"
✅ Use when you need ordering + frequent updates
2. Tuples – Immutable Sequences
- Ordered, immutable, allows duplicates
- Good for fixed data: coordinates, database keys, function returns
point = (10, 20, 30)
✅ Use when you want read-only, hashable data
3. Sets – Unique Collections
- Unordered, mutable, no duplicates
- Perfect for removing duplicates, membership tests, set math
numbers = {1, 2, 3, 3}
print(numbers) # {1, 2, 3}
✅ Use when uniqueness matters
4. Dictionaries – Key-Value Store
- Unordered, mutable, fast lookups
- Best for JSON-like data, configs, mappings
user = {"name": "Alice", "age": 25}
print(user["name"])
✅ Use for labeled, structured data
5. Strings – Special Sequence
- Technically immutable sequences of characters
- Supports slicing, concatenation, regex
s = "Python"
print(s[::-1]) # nohtyP
✅ Use as text data or character sequences
6. Arrays (from array
module)
- Similar to lists but store only one data type
- More memory-efficient for large numeric data
import array
nums = array.array("i", [1, 2, 3])
✅ Use when dealing with big numeric datasets
7. Stacks & Queues (from collections
)
- Deque provides efficient O(1) operations from both ends
from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0) # [0, 1, 2, 3]
dq.pop() # removes 3
✅ Use for queue, stack, sliding window problems
8. Priority Queues (from heapq
)
- Implements a min-heap efficiently
import heapq
nums = [5, 1, 3]
heapq.heapify(nums)
heapq.heappush(nums, 0)
✅ Use for scheduling, shortest-path algorithms
9. Counters & Defaultdict (from collections
)
- Counter → counts frequency of elements
- defaultdict → avoids key errors by setting default values
from collections import Counter, defaultdict
print(Counter("banana")) # Counter({'a':3,'n':2,'b':1})
d = defaultdict(int)
d["x"] += 1
✅ Use for frequency counts, safe dictionary access
10. Namedtuple & Dataclass
- namedtuple → lightweight, immutable object-like tuples
- dataclass → modern, flexible replacement for defining classes
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(10, 20)
✅ Use for structured, readable data
11. Frozenset – Immutable Set
- Like sets, but immutable & hashable
fs = frozenset([1, 2, 3])
✅ Use for fixed unique collections
12. Linked Lists, Trees, Graphs (Custom Implementations)
- Not built-in but can be implemented via classes
- Useful in algorithmic problems, custom structures, networking