Courses/Python Mastery/Module 5: Data Structures
Module 5 ยท Lesson 530 minBeginner๐Ÿงช Practice Session

๐Ÿงช Practice: Data Structures

Lesson goal
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

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

code
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):

code
names = ["Aarav", "Diya", "Aarav", "Kabir", "Diya", "Aarav"]
# Expected: 3 duplicates

Exercise 4 โ€” The phone book

Build this dict, then:

  • Print Kabir's phone
  • Add yourself with a number
  • Print each contact as "Name: number" using .items()
  • code
    contacts = {
        "Aarav": "9876543210",
        "Diya": "9812345678",
        "Kabir": "9898989898",
    }

    Exercise 5 โ€” Word counter

    Count how many times each word appears:

    code
    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)

    code
    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).

    code
    Expected:
    Aarav: 84.3
    Diya: 91.7
    Kabir: 75.0
    Topper: Diya

    Solutions

    Exercise 1:

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

    code
    top3 = sorted(scores, reverse=True)[:3]
    print(top3)        # sorted() makes a NEW list โ€” original untouched

    Exercise 3:

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

    Exercise 4:

    code
    print(contacts["Kabir"])
    contacts["Galvan"] = "9900112233"
    
    for name, number in contacts.items():
        print(f"{name}: {number}")

    Exercise 5:

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

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