Lesson 15
Collections Practice — Interview Programs
Final revision covering list, tuple, set, frozenset, and dictionary with interview-style coding problems.
What you will learn
Final revision covering list, tuple, set, frozenset, and dictionary with interview-style coding problems.
This is lesson 15 in the Collections Deep Dive roadmap — capstone practice after Files 02–14.
| Guided program | Skill tested |
|---|---|
| 1 | Deduplicate with set |
| 2 | List method chain |
| 3 | Set algebra |
| 4 | Nested dict CRUD |
| 5 | Hashability checker |
Revision workflow
Interview habit: Predict the output before executing the code.
- Predict — read the code and guess the result
- Run — execute in the playground
- Check — compare actual vs predicted output
- Classify — name the collection type and methods used
Program 1: Unique sorted marks
Concept: Remove duplicates using set() and sort them.
marks = [85, 90, 85, 78, 90, 92]
unique = sorted(set(marks))
print(unique)Output:
[78, 85, 90, 92]Time complexity: O(n log n) — dominated by sorted().
Need order preserved? Use list(dict.fromkeys(marks)) instead.
Program 2: List method chain
Concept: Multiple list operations in one flow.
lst = [10, 20, 30]
lst.append(40)
lst.insert(1, 15)
lst.extend([50, 60])
lst.sort()
print(lst)
print(lst.count(10), lst.index(15))Output:
[10, 15, 20, 30, 40, 50, 60]
1 1Methods used
| Method | Purpose |
|---|---|
append() |
Add one element at end |
insert() |
Add at index |
extend() |
Add multiple elements |
sort() |
Sort in place |
count() |
Frequency |
index() |
Position |
Review: File 02 — List Add and Remove · File 04 — Sort and Copy.
Program 3: Set algebra
cricket = {"A", "B", "C", "D"}
tennis = {"C", "D", "E", "F"}
print(cricket | tennis)
print(cricket & tennis)
print(cricket - tennis)
print(cricket ^ tennis)| Operator | Meaning | Result |
|---|---|---|
| Union (` | `) | All unique players |
Intersection (&) |
Players in both sports | C D |
Difference (-) |
Only cricket | A B |
Symmetric (^) |
Exactly one sport | A B E F |
Review: File 10 — Set Algebra.
Program 4: Nested dictionary CRUD
student = {
"sno": 101,
"name": "RS",
"IntMarks": {"Math": 18, "Sci": 17},
"ExtMarks": {"Math": 72, "Sci": 70},
}
student["IntMarks"]["Eng"] = 19
student["ExtMarks"]["Eng"] = 68
print(student["IntMarks"].get("Math"))
print(list(student.keys()))Structure visualization
CRUD operations
# Create
student["IntMarks"]["DBMS"] = 20
# Read
print(student["IntMarks"]["Math"])
# Update
student["ExtMarks"]["Math"] = 75
# Delete
student["IntMarks"].pop("Sci")samples = [
[1, 2],
(1, 2),
{1, 2},
frozenset({1, 2}),
{"a": 1}
]
for obj in samples:
try:
{obj}
print(type(obj).__name__, "Hashable")
except TypeError:
print(type(obj).__name__, "Not Hashable")Expected result
| Object | Result |
|---|---|
list |
Not hashable |
tuple |
Hashable |
set |
Not hashable |
frozenset |
Hashable |
dict |
Not hashable |
Review: File 14 — Hashability Rules.
Complete collections mind map
10 interview practice problems
Try each problem before reading the solutions below.
| # | Question | Difficulty |
|---|---|---|
| 1 | Remove duplicates preserving order | ⭐ |
| 2 | Reverse a tuple | ⭐ |
| 3 | Find common elements of two lists | ⭐ |
| 4 | Count frequency using dict | ⭐⭐ |
| 5 | Merge two dictionaries | ⭐⭐ |
| 6 | Find highest scoring student | ⭐⭐ |
| 7 | Group students by department | ⭐⭐⭐ |
| 8 | Nested employee CRUD | ⭐⭐⭐ |
| 9 | Validate hashability of objects | ⭐⭐⭐ |
| 10 | Convert list → set → tuple pipeline | ⭐⭐⭐ |
Solution sketches
1 — Dedupe preserving order:
lst = ["a", "b", "a", "c"]
print(list(dict.fromkeys(lst)))2 — Reverse a tuple:
t = (1, 2, 3, 4)
print(t[::-1]) # (4, 3, 2, 1)
print(tuple(reversed(t)))3 — Common elements:
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
print(list(set(a) & set(b)))4 — Frequency dict:
words = ["apple", "banana", "apple"]
freq = {}
for w in words:
freq[w] = freq.get(w, 0) + 1
print(freq)5 — Merge dicts:
d1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 3}
d1.update(d2)
print(d1)6 — Highest scoring student:
scores = {"Asha": 88, "Ravi": 92, "Meera": 85}
top = max(scores, key=scores.get)
print(top, scores[top])7 — Group by department:
students = [
{"name": "Asha", "dept": "CSE"},
{"name": "Ravi", "dept": "ECE"},
{"name": "Meera", "dept": "CSE"},
]
groups = {}
for s in students:
groups.setdefault(s["dept"], []).append(s["name"])
print(groups)8 — Nested employee CRUD:
employees = {"E101": {"name": "Asha", "dept": {"title": "Engineer"}}}
employees["E101"]["dept"]["title"] = "Senior Engineer"
employees["E102"] = {"name": "Ravi", "dept": {"title": "Analyst"}}
print(employees["E101"]["dept"]["title"])9 — Validate hashability:
def is_hashable(obj):
try:
hash(obj)
return True
except TypeError:
return False10 — List → set → tuple pipeline:
data = [10, 5, 10, 3, 5]
result = tuple(sorted(set(data)))
print(result) # (3, 5, 10)Collections revision sheet
| Type | Properties | Key methods |
|---|---|---|
| List | Ordered · Mutable · Duplicates | append(), insert(), extend(), sort() |
| Tuple | Ordered · Immutable | count(), index() |
| Set | Unique · Mutable | ` |
| Frozenset | Unique · Immutable · Hashable | Dict keys, nested sets |
| Dictionary | Key–Value · Mutable | get(), items(), update(), pop() |
Interactive knowledge check
Q1: Best way to remove duplicates while preserving order?
Answer: list(dict.fromkeys(lst)) — not list(set(lst)) (loses order) or tuple(lst) (no dedupe).
Q2: Which collection is immutable and hashable?
Answer: frozenset — not list or mutable set.
Q3: Safest way to read a missing dictionary key?
Answer: d.get("key", default) — not d["key"] (KeyError) or d.pop("key") (removes).
Q4: Which object can be a set element?
Answer: (1, 2) — not [1, 2] or {"a": 1} (unhashable).
Final takeaway
If you master these five themes, you cover most Python collection interview basics:
- Deduplication —
set,dict.fromkeys - List manipulation —
append,insert,extend,sort - Set algebra —
|,&,-,^ - Nested dictionary CRUD — multi-level keys
- Hashability rules — what can be a dict key or set member
Module complete
You can now:
- Choose the right collection for each task
- Apply pre-defined methods confidently
- Nest structures safely
- Avoid hashability bugs in interviews
Back to overview: Collections Deep Dive — File 01
Quick refresh by topic:
- Lists → Files 02–05
- Tuples → Files 06–07
- Sets → Files 08–10
- Frozenset → File 11
- Dicts → Files 12–13
- Hashability → File 14
Loading playground…