In [ ]:
# Initialize Otter
import otter
grader = otter.Notebook("09_lab_advanced_list_methods.ipynb")

Lab 09: CanesFest Operations

The CanesFest 2026 lineup is set — now it's time to handle the behind-the-scenes work. As the festival's operations manager, you'll organize food vendors across festival zones, analyze revenue data, rank vendor performance, and generate reports for leadership.

You'll use advanced list operations — slicing, sorting with lambda, aggregates, and list comprehension — to solve realistic festival logistics problems.

Run every cell in order from top to bottom. Later cells may depend on earlier ones.


In [ ]:
# Validation: Check Python version and file location
import os
import sys

# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"

if current_version not in SUPPORTED_VERSIONS:
    raise EnvironmentError(
        f"Python version mismatch!\n"
        f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
        f"Found: {current_version}\n"
        f"Please use Python 3.12 or 3.13 for this course."
    )
print(f"Python version: {current_version}")

# Expected filename for this assignment
EXPECTED_FILE = "09_lab_advanced_list_methods.ipynb"

# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lab_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)

if required_path_segment not in current_path and not in_allowed_env:
    raise EnvironmentError(
        f"File location error!\n"
        f"This notebook should be in: ~/Documents/CSC115/lab_notebooks/\n"
        f"Current location: {current_path}\n"
        f"Please move this file to the correct directory."
    )

# Verify filename (skip in grading/development environments)
if not in_allowed_env:
    if not os.path.exists(EXPECTED_FILE):
        notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
        raise EnvironmentError(
            f"Filename mismatch!\n"
            f"Expected: {EXPECTED_FILE}\n"
            f"Found notebooks: {notebooks}\n"
            f"Please rename your notebook to '{EXPECTED_FILE}'."
        )

print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
In [ ]:
# ── Vendor data column indices ──────────────────────────────────────────
# Each vendor is a tuple: (name, zone, daily_revenue, food_type, setup_fee)
NAME = 0
ZONE = 1
DAILY_REVENUE = 2
FOOD_TYPE = 3
SETUP_FEE = 4

# ── CanesFest 2026 Vendor List ──────────────────────────────────────────
vendors = [
    ("Tropical Bites", "Main", 2800, "caribbean", 500),
    ("Cane's Grill", "Main", 3200, "bbq", 600),
    ("Miami Squeeze", "Main", 1900, "drinks", 300),
    ("Churro Kingdom", "Coral", 2100, "dessert", 350),
    ("Island Bowls", "Coral", 2600, "healthy", 450),
    ("Taco Libre", "Coral", 3100, "mexican", 550),
    ("Boba Bliss", "Palm", 1700, "drinks", 250),
    ("Pizza Party", "Palm", 2400, "pizza", 400),
    ("Empanada Express", "Palm", 2000, "latin", 350),
    ("Smoothie Surf", "Main", 1500, "drinks", 200),
    ("Wing Shack", "Coral", 2900, "american", 500),
    ("Arepa Ave", "Palm", 1800, "latin", 300),
]

print(f"Loaded {len(vendors)} vendors")
print(f"Example: {vendors[0][NAME]} in {vendors[0][ZONE]} zone — ${vendors[0][DAILY_REVENUE]}/day")

Quick Reference

Pattern Syntax Example
Slice a list list[start:stop] vendors[:4]
Copy a list list[:] vendors[:]
Insert at position .insert(index, item) my_list.insert(5, new_item)
Remove and return .pop(index) removed = my_list.pop(3)
Sort with key sorted(list, key=lambda x: x[FIELD]) sorted(vendors, key=lambda v: v[DAILY_REVENUE])
Reverse sort sorted(..., reverse=True) sorted(vendors, key=lambda v: v[DAILY_REVENUE], reverse=True)
Aggregate sum([expr for x in list]) sum([v[DAILY_REVENUE] for v in vendors])
Filter [x for x in list if cond] [v for v in vendors if v[ZONE] == "Main"]
Transform [expr for x in list] [v[NAME] for v in vendors]

Batch A: Vendor Setup

These first two questions handle vendor organization and last-minute changes. Q2 builds on Q1.


Q1: Inspection Schedule

You need to split the vendor list into three groups for scheduling walkthrough inspections. The first 4 vendors on the list will be inspected in the morning, the next 4 at midday, and the last 4 in the afternoon.

✏️ Your tasks:

  1. Use slicing to create morning_vendors containing the first 4 vendors.
  2. Use slicing to create midday_vendors containing the next 4 vendors (indices 4-7).
  3. Use slicing to create afternoon_vendors containing the last 4 vendors.
  4. Create working_vendors, a complete copy of the vendors list that you can safely modify without affecting the original.
In [ ]:
# ✏️ YOUR ANSWER HERE

morning_vendors = ...
midday_vendors = ...
afternoon_vendors = ...
working_vendors = ...

print(f"Morning inspection ({len(morning_vendors)} vendors):")
for v in morning_vendors:
    print(f"  {v[NAME]}")
print(f"\nMidday inspection ({len(midday_vendors)} vendors):")
for v in midday_vendors:
    print(f"  {v[NAME]}")
print(f"\nAfternoon inspection ({len(afternoon_vendors)} vendors):")
for v in afternoon_vendors:
    print(f"  {v[NAME]}")
print(f"\nWorking copy has {len(working_vendors)} vendors")
In [ ]:
grader.check("q1_zone_setup")

Q2: Last-Minute Changes

A last-minute vendor swap! A new vendor needs to be added and a cancellation needs to be handled — all on your working_vendors copy from Q1.

✏️ Your tasks:

  1. Create a tuple for the new vendor: ("Havana Nights", "Main", 2700, "cuban", 475) and store it in havana.
  2. Insert havana at position 5 in working_vendors.
  3. The vendor at index 9 just cancelled — use .pop(9) to remove them and store the removed vendor in cancelled_vendor.
  4. Store the updated vendor count in updated_vendor_count.
In [ ]:
# ✏️ YOUR ANSWER HERE

havana = ...
...
cancelled_vendor = ...
updated_vendor_count = ...

print(f"Added: {havana[NAME]}")
print(f"Cancelled: {cancelled_vendor[NAME]}")
print(f"Updated vendor count: {updated_vendor_count}")
print("\nUpdated vendor list:")
for i, v in enumerate(working_vendors):
    print(f"  [{i}] {v[NAME]}")
In [ ]:
grader.check("q2_vendor_changes")

Batch B: Sorting & Revenue Analysis

These three questions focus on sorting vendors by different criteria and computing aggregate statistics. All questions in this batch use the original vendors list (not working_vendors).


Q3: Revenue Rankings

Festival leadership wants a revenue report. Rank all vendors from highest daily revenue to lowest.

✏️ Your tasks:

  1. Create by_revenue — a new list with all vendors sorted from highest daily revenue to lowest. Use sorted() with a lambda function as the key.
  2. Create top_three_names — a list of just the vendor names (strings) for the top 3 revenue earners. Extract these from by_revenue using slicing and a list comprehension.
In [ ]:
# ✏️ YOUR ANSWER HERE

by_revenue = ...
top_three_names = ...

print("Vendors by revenue (highest to lowest):")
for v in by_revenue:
    print(f"  {v[NAME]}: ${v[DAILY_REVENUE]}")
print(f"\nTop 3: {top_three_names}")
In [ ]:
grader.check("q3_revenue_sort")

Q4: Vendor Efficiency

Revenue alone doesn't tell the full story. Festival leadership wants to know which vendors are the most efficient — meaning which vendors get the most out of every dollar they spend on setup.

Think about it this way: if two vendors both earn $2000 in a day, but one paid $200 to set up and the other paid $500, the first vendor is clearly getting more bang for their buck. For every dollar Vendor A spent on setup, they earned back many more dollars in revenue than Vendor B did.

Your job is to figure out how to measure this "bang for your buck" and use it to rank the vendors.

Hint: the answer might surprise you — the vendor with the highest revenue is not necessarily the most efficient!

✏️ Your tasks:

  1. Create by_efficiency — all vendors sorted from most efficient to least efficient using sorted() with a lambda.
  2. Use max() with a key=lambda to find the single most efficient vendor tuple. Store it in most_efficient.
  3. Use min() with a key=lambda to find the least efficient vendor tuple. Store it in least_efficient.
In [ ]:
# ✏️ YOUR ANSWER HERE

by_efficiency = ...
most_efficient = ...
least_efficient = ...

print("Vendors by efficiency (revenue per dollar of setup cost):")
for v in by_efficiency:
    ratio = v[DAILY_REVENUE] / v[SETUP_FEE]
    print(f"  {v[NAME]}: ${v[DAILY_REVENUE]} / ${v[SETUP_FEE]} = {ratio:.2f}x")
print(f"\nMost efficient: {most_efficient[NAME]}")
print(f"Least efficient: {least_efficient[NAME]}")
In [ ]:
grader.check("q4_efficiency")

Q5: Festival Revenue Report

Time to generate the revenue report for festival leadership. Use aggregate functions (sum, max) combined with list comprehension to compute summary statistics from the original vendors list.

✏️ Your tasks:

  1. Calculate total_revenue — the sum of all vendors' daily revenue.
  2. Calculate highest_revenue — the single highest daily revenue value among all vendors.
  3. Calculate avg_revenue — the average daily revenue across all vendors (total divided by count).
  4. Calculate total_profit — the sum of all vendors' profit, where profit = revenue minus setup fee for each vendor.
In [ ]:
# ✏️ YOUR ANSWER HERE

total_revenue = ...
highest_revenue = ...
avg_revenue = ...
total_profit = ...

print(f"Total daily revenue: ${total_revenue}")
print(f"Highest single vendor revenue: ${highest_revenue}")
print(f"Average vendor revenue: ${avg_revenue:.2f}")
print(f"Total daily profit: ${total_profit}")
In [ ]:
grader.check("q5_revenue_report")

Independent Questions: List Comprehension

These questions are independent — they don't depend on your answers from Batch A or B. If you're stuck on an earlier question, skip ahead to these.


Q6: Filtering Vendors

Festival organizers want to identify high-performing vendors and drink vendors separately. Use list comprehension with filtering to create new lists from the original vendors list.

✏️ Your tasks:

  1. Create high_earners — a list of vendor tuples where daily revenue is at least $2500.
  2. Create drink_vendor_names — a list of just the names (strings) of vendors whose food type is "drinks".
In [ ]:
# ✏️ YOUR ANSWER HERE

high_earners = ...
drink_vendor_names = ...

print(f"High earners (${2500}+ daily):")
for v in high_earners:
    print(f"  {v[NAME]}: ${v[DAILY_REVENUE]}")
print(f"\nDrink vendors: {drink_vendor_names}")
In [ ]:
grader.check("q6_filter_vendors")

Q7: VIP Vendor Report

For the VIP sponsor packet, leadership needs a polished summary of the top-performing vendors. This question combines filtering, string formatting, aggregates, and sorting — all the skills from this lab in one place.

✏️ Your tasks:

  1. Create vip_summary — a list of formatted strings for vendors earning at least $2500 per day. Each string should follow the format `"{name}: ${revenue}"(e.g.,"Cane's Grill: $3200"`). Use a single list comprehension that filters and transforms.
  2. Calculate vip_avg_revenue — the average daily revenue of only those vendors earning at least $2500.
  3. Create vip_sorted — the same high-earning vendors (full tuples, not strings), sorted by daily revenue from highest to lowest.
In [ ]:
# ✏️ YOUR ANSWER HERE

vip_summary = ...
vip_avg_revenue = ...
vip_sorted = ...

print("VIP Vendor Report:")
for line in vip_summary:
    print(f"  {line}")
print(f"\nVIP average revenue: ${vip_avg_revenue:.2f}")
print("\nVIP vendors ranked:")
for v in vip_sorted:
    print(f"  {v[NAME]}: ${v[DAILY_REVENUE]}")
In [ ]:
grader.check("q7_vip_report")

Summary

Concept Syntax What it does
Slice a list list[start:stop] Extracts a portion (new list)
Copy a list list[:] Creates a shallow copy
Insert .insert(index, item) Adds item at position, shifts others right
Pop .pop(index) Removes and returns item at position
Sort (new list) sorted(list, key=lambda x: ...) Returns a new sorted list
Reverse sort sorted(..., reverse=True) Sorts from highest to lowest
Max with key max(list, key=lambda x: ...) Returns the item with the largest key
Min with key min(list, key=lambda x: ...) Returns the item with the smallest key
Sum sum([expr for x in list]) Totals values from a comprehension
Filter [x for x in list if cond] Keeps only items matching condition
Transform [expr for x in list] Applies expression to each item
Filter + Transform [expr for x in list if cond] Both in one line

Submitting to Gradescope

This file is saved on your computer — you do not need to download it from Jupyter.

  1. Find the file on your computer:

    • Mac: Open Finder → Documents/CSC115/lab_notebooks/09_lab_advanced_list_methods/09_lab_advanced_list_methods.ipynb
    • Windows: Open File Explorer → Documents\CSC115\lab_notebooks\09_lab_advanced_list_methods\09_lab_advanced_list_methods.ipynb
  2. Upload to Gradescope:

    • Go to gradescope.com and open this assignment
    • Click "Submit" and upload the .ipynb file
    • The filename must be exactly 09_lab_advanced_list_methods.ipynb

Do NOT use File > Download in Jupyter — this can rename the file and cause submission errors.


You have completed the Lab 09: CanesFest Operations notebook.


To double-check your work, the cell below will rerun all of the autograder tests.

In [ ]:
grader.check_all()