Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 15

Collections Practice — Interview Programs

Final revision covering list, tuple, set, frozenset, and dictionary with interview-style coding problems.

Intermediate30 min

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

Predict Run Check Classify interview workflow

Interview habit: Predict the output before executing the code.

  1. Predict — read the code and guess the result
  2. Run — execute in the playground
  3. Check — compare actual vs predicted output
  4. Classify — name the collection type and methods used

Program 1: Unique sorted marks

Concept: Remove duplicates using set() and sort them.

python
marks = [85, 90, 85, 78, 90, 92]

unique = sorted(set(marks))
print(unique)

Output:

text
[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.

python
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:

text
[10, 15, 20, 30, 40, 50, 60]
1 1

Methods 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

python
cricket = {"A", "B", "C", "D"}
tennis = {"C", "D", "E", "F"}

print(cricket | tennis)
print(cricket & tennis)
print(cricket - tennis)
print(cricket ^ tennis)
Set algebra union intersection difference symmetric summary
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

python
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

Nested student IntMarks ExtMarks structure

CRUD operations

python
# Create
student["IntMarks"]["DBMS"] = 20

# Read
print(student["IntMarks"]["Math"])

# Update
student["ExtMarks"]["Math"] = 75

# Delete
student["IntMarks"].pop("Sci")

Review: File 13 — Nested Dictionaries.


Program 5: Hashability checker

python
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

Collections mind map list tuple set frozenset dict

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:

python
lst = ["a", "b", "a", "c"]
print(list(dict.fromkeys(lst)))

2 — Reverse a tuple:

python
t = (1, 2, 3, 4)
print(t[::-1])          # (4, 3, 2, 1)
print(tuple(reversed(t)))

3 — Common elements:

python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
print(list(set(a) & set(b)))

4 — Frequency dict:

python
words = ["apple", "banana", "apple"]
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
print(freq)

5 — Merge dicts:

python
d1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 3}
d1.update(d2)
print(d1)

6 — Highest scoring student:

python
scores = {"Asha": 88, "Ravi": 92, "Meera": 85}
top = max(scores, key=scores.get)
print(top, scores[top])

7 — Group by department:

python
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:

python
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:

python
def is_hashable(obj):
    try:
        hash(obj)
        return True
    except TypeError:
        return False

10 — List → set → tuple pipeline:

python
data = [10, 5, 10, 3, 5]
result = tuple(sorted(set(data)))
print(result)   # (3, 5, 10)

Collections revision sheet

Five collection type revision cards
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:

  1. Deduplication — set, dict.fromkeys
  2. List manipulation — append, insert, extend, sort
  3. Set algebra — |, &, -, ^
  4. Nested dictionary CRUD — multi-level keys
  5. 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:

Loading playground…