Collections in Python
Subject: Data Structures and Algorithms · Language: Python · Level: beginner · 8 min read
Understand Python collections with teacher-style explanation of list, tuple, set, dict, deque, Counter, defaultdict, heapq, and DSA use cases.
Collections are data structures used to store multiple values. Python provides several collections, and each one is designed for a different kind of problem. Choosing the correct collection can make a solution easier and faster.
A list stores values in order and allows index access. Use it when order matters or when you need to process elements by position. Lists are common for arrays, input values, sorting, prefix sums, and two-pointer problems.
A tuple is like a list, but immutable. Once created, it cannot be changed. Tuples are useful for fixed groups of values, such as coordinates, pairs, or records that should not be modified accidentally.
A set stores unique values. It is useful when you need fast membership checking or duplicate removal. For example, checking whether a number has already appeared can be done efficiently using a set.
A dictionary stores key-value pairs. It is very useful for frequency counting, mapping names to marks, storing visited states, or quickly finding related information using a key.
Python also provides tools like `Counter`, `defaultdict`, `deque`, and `heapq`. These are helpful in DSA, but students should first understand the basic idea: list for order, set for uniqueness, dictionary for mapping, deque for queue behavior, and heap for priority.
Collections are data structures used to store and process groups of values. In real programs, we rarely work with only one value. We usually store many numbers, names, records, unique values, key-value pairs, or tasks waiting to be processed.
Python gives several ready-made collections. The most common built-in collections are `list`, `tuple`, `set`, and `dict`. Python also provides useful collection tools such as `deque`, `Counter`, and `defaultdict` from the `collections` module, and `heapq` for heap or priority queue logic.
For DSA, collections are very important because choosing the correct collection can make a solution simpler and faster. But students should still understand the concept behind each collection. Built-in tools should support your logic, not replace your understanding.
Why Collections Are Needed
Suppose you need to store marks of 50 students. Creating 50 separate variables is not practical. A collection lets you store all related values together and process them using loops and methods.
Different collections solve different problems. If order and index matter, use a list. If uniqueness matters, use a set. If key-value mapping matters, use a dictionary. If queue behavior matters, use a deque.
List
A list is an ordered and mutable collection. Ordered means values stay in sequence. Mutable means values can be changed after creation.
```python
numbers = [10, 20, 30]
numbers.append(40)
```
Lists are used when you need array-style storage, index access, traversal, sorting, or dynamic size.
In DSA, lists are used for array problems, prefix sums, sliding window, two pointers, sorting, searching, stacks, and many dynamic programming problems.
Important List Operations
- `append(value)` adds a value at the end
- `pop()` removes the last value
- `sort()` sorts the list in place
- `len(list)` gives the number of elements
- `list[index]` accesses a value by position
A list is flexible, but not every operation is equally fast. Accessing by index is fast. Removing from the front using `pop(0)` is slow for large input because elements shift left.
Tuple
A tuple is ordered but immutable. This means values cannot be changed after the tuple is created.
```python
pair = (10, 20)
```
Tuples are useful when values should stay grouped together. For example, coordinates like `(row, col)` or heap items like `(distance, node)` are often stored as tuples.
Use a tuple when the grouped values represent one fixed unit and you do not need to modify it.
Set
A set stores unique values. Duplicate values are automatically removed.
```python
values = {10, 20, 20, 30}
print(values)
```
Output
```text
{10, 20, 30}
```
The display order of a set can vary, but duplicate `20` is stored only once.
A set is useful when you need fast existence checking or uniqueness.
For example, if you want to check whether a number has appeared before, a set is better than scanning a list again and again.
Set in DSA
Sets are commonly used for duplicate detection, visited tracking in graphs, unique element problems, and fast membership checks.
```python
seen = set()
for value in arr:
if value in seen:
print("Duplicate found")
seen.add(value)
```
Sample Output when `arr = [5, 8, 5]`
```text
Duplicate found
```
Checking `value in seen` is usually much faster than checking inside a list for large input.
Dictionary
A dictionary stores data in key-value pairs. A key is used to quickly find its value.
```python
marks = {"Rahul": 85, "Priya": 92}
print(marks["Rahul"])
```
Output
```text
85
```
Dictionaries are extremely useful in DSA because many problems need mapping. For example, mapping a number to its frequency, a character to its count, or a node to its neighbors.
Frequency Counting with Dictionary
Frequency means how many times a value appears. A dictionary is commonly used for frequency counting.
```python
arr = [1, 2, 2, 3, 1]
freq = {}
for value in arr:
freq[value] = freq.get(value, 0) + 1
```
Here, `freq.get(value, 0)` gives the current count if the value already exists, otherwise it gives 0.
After the loop, `freq` stores each number and how many times it appeared.
Counter
`Counter` from the `collections` module makes frequency counting shorter.
```python
from collections import Counter
arr = [1, 2, 2, 3, 1]
freq = Counter(arr)
```
Counter is useful in string problems, anagram problems, frequency comparison, and counting repeated values.
Even when using Counter, students should understand the dictionary counting logic behind it.
deque
`deque` stands for double-ended queue. It allows efficient insertion and deletion from both ends.
```python
from collections import deque
queue = deque()
queue.append(10)
queue.append(20)
print(queue.popleft())
```
Output
```text
10
```
Use `deque` for queue problems, BFS, sliding window, and situations where removing from the front is needed.
A Python list can remove from the front using `pop(0)`, but that is slow for large input. `deque.popleft()` is the better queue operation.
defaultdict
`defaultdict` gives a default value automatically when a missing key is used.
```python
from collections import defaultdict
graph = defaultdict(list)
graph[1].append(2)
```
This is commonly used in graph adjacency lists and grouping problems. Without `defaultdict`, we often need to check whether a key exists before appending.
heapq
`heapq` provides heap operations. It is commonly used for priority queue problems.
```python
import heapq
heap = []
heapq.heappush(heap, 5)
heapq.heappush(heap, 2)
print(heapq.heappop(heap))
```
Output
```text
2
```
Python's heap gives the smallest value first by default. This is called a min-heap.
Heap is useful when you repeatedly need the smallest or highest-priority value, such as in shortest path, top-k elements, and scheduling problems.
Choosing the Right Collection
Use `list` when order and index access matter. Use `tuple` when grouped values should not change. Use `set` when uniqueness and fast membership checking matter. Use `dict` when key-value mapping or frequency counting is needed. Use `deque` for queue behavior. Use `heapq` for priority-based removal.
Choosing the correct collection can reduce time complexity and make the solution easier to read.
Example Program
```python
numbers = []
numbers.append(10)
numbers.append(20)
numbers.append(30)
for value in numbers:
print(value, end=" ")
print()
```
Output
```text
10 20 30
```
This program creates a list, adds three values, and prints them using a loop. The same style is commonly used when processing dynamic input values.
Collections in DSA
Collections appear everywhere in DSA. Lists store arrays. Sets track visited nodes. Dictionaries count frequencies. Deques support BFS. Heaps support priority queues and shortest path algorithms.
A strong Python DSA student should know not only the syntax, but also when and why each collection is used.
Python collections should be chosen based on the problem requirement. A list is best when order and index access matter. A set is best when uniqueness and fast membership checking matter. A dictionary is best when a key must quickly find a related value.
For queue problems, `deque` is usually better than a normal list because removing from the front of a list is slow. `deque.popleft()` is efficient and is commonly used in BFS and level-order traversal.
For frequency problems, a dictionary or `Counter` is useful. Instead of using nested loops to count each value again and again, store counts while traversing once. This often changes a slow solution into a faster one.
For priority-based problems, `heapq` is useful. It gives quick access to the smallest value. Problems involving repeated minimum extraction, top-k values, scheduling, and merging sorted lists often use heaps.
The important interview skill is not only knowing collection names. The important skill is explaining why one collection fits the problem better than another. That explanation shows real DSA understanding.
Practice Question
Create a list of integers, add five numbers, and print only the even numbers. Then use a set to print how many unique numbers are present. Finally, use a dictionary to count the frequency of each number.