๐งช Practice: Data Structures
The container workout. Six exercises covering lists, tuples, sets, dicts, and nesting. Solutions at the bottom โ earn them first.
Exercise 1 โ Shopping cart
cart = []
# 1. add "Milk", "Bread", "Eggs"
# 2. you forgot "Butter" โ add it to the FRONT
# 3. you changed your mind about Eggs โ remove it
# 4. print how many items and the final listExpected: 3 items: ['Butter', 'Milk', 'Bread']
Exercise 2 โ Top three
Given scores, print the top 3 in descending order without changing the original list:
scores = [45, 89, 72, 95, 60, 95]
# Expected: [95, 95, 89]Exercise 3 โ Duplicate hunter
Count how many duplicates exist in a list (total length minus unique count):
names = ["Aarav", "Diya", "Aarav", "Kabir", "Diya", "Aarav"]
# Expected: 3 duplicatesExercise 4 โ The phone book
Build this dict, then:
contacts = {
"Aarav": "9876543210",
"Diya": "9812345678",
"Kabir": "9898989898",
}Exercise 5 โ Word counter
Count how many times each word appears:
text = "the quick brown fox jumps over the lazy dog the end"
# Expected: {'the': 3, 'quick': 1, 'brown': 1, ...}*(Hint: split the text into words, then use a dict with the pattern: if word in counts: counts[word] += 1, else counts[word] = 1)*
Exercise 6 โ The class topper (nested)
students = [
{"name": "Aarav", "marks": [85, 90, 78]},
{"name": "Diya", "marks": [95, 88, 92]},
{"name": "Kabir", "marks": [70, 75, 80]},
]For each student, print their name and average marks. Then print the name of the overall topper (highest average).
Expected:
Aarav: 84.3
Diya: 91.7
Kabir: 75.0
Topper: DiyaSolutions
Exercise 1:
cart = []
cart.append("Milk")
cart.append("Bread")
cart.append("Eggs")
cart.insert(0, "Butter")
cart.remove("Eggs")
print(f"{len(cart)} items: {cart}")Exercise 2:
top3 = sorted(scores, reverse=True)[:3]
print(top3) # sorted() makes a NEW list โ original untouchedExercise 3:
duplicates = len(names) - len(set(names))
print(duplicates) # 3Exercise 4:
print(contacts["Kabir"])
contacts["Galvan"] = "9900112233"
for name, number in contacts.items():
print(f"{name}: {number}")Exercise 5:
words = text.split()
counts = {}
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(counts)(This counting pattern โ check, increment or initialize โ is one of the most reused in all of programming.)
Exercise 6:
topper_name = ""
topper_avg = 0
for s in students:
avg = sum(s["marks"]) / len(s["marks"])
print(f"{s['name']}: {avg:.1f}")
if avg > topper_avg:
topper_avg = avg
topper_name = s["name"]
print(f"Topper: {topper_name}")Note the nested access: s["marks"] gets the list, then sum() and len() work on it โ list inside dict, handled layer by layer.
โ Module 5 Checkpoint
Six done? You now wield the full container toolbox โ lists for order, tuples for permanence, sets for uniqueness, dicts for labels, and nesting for the real world.
Next module: Control Flow โ the if/loop machinery that makes data do things.