Tech With Galvan
Courses/Python Mastery/Data Structures

πŸ§ͺ Practice: Data Structures

30 min β€’ Beginner β€’ Module 5

Exercises: shopping cart, contact book, dedupe a list, and navigate nested data.

πŸ§ͺ 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 list

Expected: 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 duplicates

Exercise 4 β€” The phone book

Build this dict, then:

  1. Print Kabir’s phone
  2. Add yourself with a number
  3. Print each contact as β€œName: number” using .items()
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: Diya

Solutions

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 untouched

Exercise 3:

duplicates = len(names) - len(set(names))
print(duplicates)        # 3

Exercise 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.