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

Advanced List Operations

Theme: CanesFest 2026 — Building a music festival lineup

Goal: Learn advanced list operations — slicing, insert(), pop(), sorting with lambda, shallow vs deep copy, aggregate functions, and list comprehension for transformations, filtering, and combined operations.

By the end of this notebook, you will be able to:

  • Extract portions of lists and strings using slicing (list[start:stop:step])
  • Add and remove items at specific positions with insert() and pop()
  • Sort lists with sorted() and .sort(), including custom sort keys with lambda
  • Explain why list_b = list_a creates an alias (not a copy) and use .copy() or [:] to fix it
  • Use built-in aggregate functions: sum(), min(), max()
  • Write list comprehensions for transformations, filtering, and combined operations

Reference: You can look back at 05_lecture_for_loops.ipynb for list iteration basics and 06_lecture_functions.ipynb for tuples with index constants!

Important: Run cells in order from top to bottom. Later questions use variables from earlier cells.

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 = "08_lecture_advanced_lists.ipynb"

# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_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/lecture_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)}")

CanesFest 2026 Lineup Data

You're helping organize CanesFest 2026, a University of Miami music festival. The lineup is stored as a list of tuples with index constants — the same pattern you used for whale sighting data in the File I/O lecture.

Each act is a tuple: (artist, set_time, popularity_score, genre, stage)

In [ ]:
# --- Index constants for CanesFest lineup ---
ARTIST = 0
TIME_SLOT = 1
POPULARITY = 2
GENRE = 3
STAGE = 4

# --- CanesFest 2026 Lineup ---
# Each act: (artist, set_time, popularity_score, genre, stage)
lineup = [
    ("Bad Bunny", "9:00 PM", 98, "reggaeton", "Main"),
    ("Olivia Rodrigo", "8:00 PM", 88, "pop", "Main"),
    ("Tyler the Creator", "7:00 PM", 85, "hip-hop", "Main"),
    ("Peso Pluma", "6:00 PM", 82, "regional mexican", "Coral"),
    ("Billie Eilish", "8:30 PM", 95, "pop", "Main"),
    ("Metro Boomin", "5:00 PM", 78, "hip-hop", "Coral"),
    ("Chappell Roan", "7:30 PM", 80, "pop", "Palm"),
    ("Gunna", "4:00 PM", 70, "hip-hop", "Coral"),
    ("Tyla", "6:30 PM", 76, "afrobeats", "Palm"),
    ("Rauw Alejandro", "5:30 PM", 74, "reggaeton", "Coral"),
    ("Sabrina Carpenter", "9:30 PM", 92, "pop", "Main"),
    ("Future", "4:30 PM", 72, "hip-hop", "Coral"),
    ("Karol G", "8:00 PM", 84, "reggaeton", "Main"),
    ("Ice Spice", "3:00 PM", 68, "hip-hop", "Palm"),
    ("Doja Cat", "9:00 PM", 90, "pop", "Main"),
]

print(f"Loaded {len(lineup)} acts for CanesFest 2026!")
print(f"Example: lineup[0] = {lineup[0]}")
print(f"  lineup[0][ARTIST] = '{lineup[0][ARTIST]}'")
print(f"  lineup[0][POPULARITY] = {lineup[0][POPULARITY]}")
print(f"  lineup[0][GENRE] = '{lineup[0][GENRE]}'")

1. The Big Picture

Before we dive into individual concepts, here's a complete function that generates a festival stage report using all the concepts we'll learn today:

  • Copying a list (to avoid destroying the original)
  • insert() and pop() (to modify lineups)
  • Sorting with lambda (to rank acts)
  • List slicing (to grab a portion)
  • List comprehension (to build new lists from old ones)
  • Aggregate functions (max(), min(), len())

Don't worry if you don't understand every line yet! By the end of this notebook, you'll be able to build this yourself.

In [ ]:
# THE BIG PICTURE: Festival stage report generator
# By the end of this notebook, you'll understand every line!


def stage_report(full_lineup, stage_name):
    """Generate a report for one festival stage.

    Demonstrates: copy, insert, pop, sorting, slicing, comprehension, aggregates
    """
    # Copy the lineup so we don't destroy the original
    working = full_lineup[:]

    # Last-minute change: add a surprise opener, remove a cancelled act
    working.insert(0, ("DJ Khaled", "2:00 PM", 65, "hip-hop", stage_name))
    working.pop(-1)  # Last act cancelled

    # Filter to just this stage (list comprehension with a condition)
    stage_acts = [act for act in working if act[STAGE] == stage_name]

    # Sort alphabetically by artist name
    stage_acts_sorted = sorted(stage_acts, key=lambda act: act[ARTIST])

    # Grab the first 3 alphabetically (slicing)
    first_three = stage_acts_sorted[:3]

    # Build display names (transformation comprehension)
    display_names = [act[ARTIST].upper() for act in first_three]

    # Aggregate stats
    top_act = max(stage_acts, key=lambda act: act[POPULARITY])
    weakest = min(stage_acts, key=lambda act: act[POPULARITY])

    print(f"=== {stage_name} Stage Report ===")
    print(f"Acts on this stage: {len(stage_acts)}")
    print(f"Top draw: {top_act[ARTIST]} (popularity {top_act[POPULARITY]})")
    print(f"Opener: {weakest[ARTIST]} (popularity {weakest[POPULARITY]})")
    print(f"First 3 alphabetically: {display_names}")
    print(f"Original lineup still has {len(full_lineup)} acts (copy kept it safe!)")


stage_report(lineup, "Main")
print()
stage_report(lineup, "Coral")

Now let's learn each piece!

We'll build up to that stage report step by step, learning each concept along the way.


Day 1: List Manipulation


2. List Slicing

You already know indexing — lineup[0] gives the first act. Slicing extends this to grab a RANGE of items at once, creating a new list.

Reading the syntax

# lineup[0:5:2]
#        ^ ^ ^
#        | | |__ step (take every 2nd item)
#        | |__ stop (up to but NOT including index 5)
#        |__ start (begin at index 0)

Same rule as range() — the stop value is the fence post you walk UP TO but never step on.

In [ ]:
# Slicing extracts a PORTION of a list
# lineup[start:stop] — start is included, stop is NOT (same as range()!)

headliners = lineup[0:3]
print("First 3 acts (headliners):")
for act in headliners:
    print(f"  {act[ARTIST]} — {act[POPULARITY]} popularity")

print(f"\nOriginal lineup still has {len(lineup)} acts (slicing never mutates!)")
In [ ]:
# Shorthand: omit start (defaults to 0) or stop (defaults to end)
first_five = lineup[:5]
last_three = lineup[-3:]
every_other = lineup[::2]

print("First 5:", [act[ARTIST] for act in first_five])
print("Last 3:", [act[ARTIST] for act in last_three])
print("Every other:", [act[ARTIST] for act in every_other])
In [ ]:
# Strings are sequences too — slicing works the same way
festival_name = "CanesFest 2026"
print(festival_name[:9])     # "CanesFest"
print(festival_name[-4:])    # "2026"
print(festival_name[::2])    # "CnsFt 06"
In [ ]:
# Step of -1 reverses the sequence
reversed_name = festival_name[::-1]
print(reversed_name)  # "6202 tseFsenaC"

reversed_lineup = lineup[::-1]
print(f"Last act first: {reversed_lineup[0][ARTIST]}")

Key point: Slicing NEVER modifies the original list — it always creates a new list. This is important and different from insert() and pop(), which we'll learn next.


Question 1: Slice the Headliners (1 point)

The first 5 acts in the lineup are the headliners. Use slicing to create a new list called headliner_acts containing just those 5.

Then use slicing to create closing_acts containing the last 3 acts in the lineup.

Finally, create reversed_headliners which is headliner_acts in reverse order (last headliner first).

Hint: Use lineup[:5], lineup[-3:], and [::-1] to reverse.

In [ ]:
# ✏️ YOUR CODE HERE
headliner_acts = ...
closing_acts = ...
reversed_headliners = ...

print("Headliners:")
for act in headliner_acts:
    print(f"  {act[ARTIST]}")
print(f"\nClosing acts:")
for act in closing_acts:
    print(f"  {act[ARTIST]}")
print(f"\nReversed headliners:")
for act in reversed_headliners:
    print(f"  {act[ARTIST]}")
In [ ]:
grader.check("q1_headliners")

3. insert() and pop()

You already know .append() adds to the END of a list. But what if you need to add at a specific position? Or remove from a specific position?

  • insert(index, item) — adds an item AT a specific position, shifting everything after it to the right
  • pop(index) — REMOVES and RETURNS the item at that position

Unlike slicing, both of these mutate (change) the original list.

In [ ]:
# .insert(index, item) adds an item AT a specific position
# Everything after it shifts right

# Work on a copy so we don't mess up the original lineup
demo_lineup = lineup[:5]  # Just headliners for readability

print("Before insert:")
for i, act in enumerate(demo_lineup):
    print(f"  [{i}] {act[ARTIST]}")

# Surprise guest! Insert Kendrick Lamar at position 2 (3rd slot)
surprise_act = ("Kendrick Lamar", "7:30 PM", 96, "hip-hop", "Main")
demo_lineup.insert(2, surprise_act)

print("\nAfter inserting Kendrick at position 2:")
for i, act in enumerate(demo_lineup):
    print(f"  [{i}] {act[ARTIST]}")
In [ ]:
# .pop(index) REMOVES and RETURNS the item at that position
# Without an index, it removes the LAST item

cancelled_demo = demo_lineup.pop(4)  # Remove the act at index 4
print(f"Cancelled: {cancelled_demo[ARTIST]}")

print("\nUpdated lineup:")
for act in demo_lineup:
    print(f"  {act[ARTIST]}")

# .pop() with no argument removes the last item
last_act_demo = demo_lineup.pop()
print(f"\nAlso removed last act: {last_act_demo[ARTIST]}")
In [ ]:
# .append() always adds to the END
# .insert() lets you choose WHERE

schedule = []
schedule.append(("Act A", "8:00 PM", 80, "pop", "Main"))
schedule.insert(0, ("Act B", "7:00 PM", 75, "pop", "Main"))  # Add to front
schedule.append(("Act C", "9:00 PM", 85, "pop", "Main"))
schedule.insert(1, ("Act D", "7:30 PM", 70, "pop", "Main"))  # Add at index 1

print("Built a schedule with insert and append:")
for i, act in enumerate(schedule):
    print(f"  [{i}] {act[ARTIST]} @ {act[TIME_SLOT]}")

Key point: Unlike slicing, insert() and pop() modify the original list. This is called mutation. Always be aware of whether an operation creates a new list or changes the existing one.

Operation Mutates original? Returns
list[a:b] (slicing) No — creates new list New list
.append(item) Yes None
.insert(i, item) Yes None
.pop(i) Yes The removed item

Question 2: Manage Lineup Changes (1 point)

Festival drama! You need to make some changes to the lineup.

  1. Start by creating a copy of lineup using slicing (call it updated_lineup). Use lineup[:] so changes don't affect the original.
  2. A new act ('Drake', '10:00 PM', 91, 'hip-hop', 'Main') has been added — insert Drake at position 2 in updated_lineup.
  3. The act at index 7 had to cancel — use pop() to remove them and store the removed act in cancelled_act.
  4. Store the total number of acts in final_count.

Hint: Create the Drake tuple first, then insert it. Remember that pop() both removes AND returns the item.

In [ ]:
# ✏️ YOUR CODE HERE
updated_lineup = ...
drake = ...
...
cancelled_act = ...
final_count = ...

print(f"Cancelled: {cancelled_act[ARTIST]}")
print(f"Final lineup count: {final_count}")
print("\nUpdated lineup:")
for i, act in enumerate(updated_lineup):
    print(f"  [{i}] {act[ARTIST]}")
In [ ]:
grader.check("q2_lineup_changes")

4. Sorting

Sorting numbers is straightforward — Python knows that 3 comes before 5. But how does Python sort our lineup tuples? It doesn't know if we want to sort by artist name, popularity, or time slot. We need to tell it which field to look at.

That's where lambda comes in.

Lambda: A Mini Function

A lambda is a one-line function without a name. It's used when you need a quick, throwaway function — most commonly to tell sorted() which field to sort by.

In [ ]:
# A lambda is just a one-line function without a name.
# These two do the EXACT same thing:

# --- Way 1: Regular function (you already know this!) ---
def get_popularity(act):
    return act[POPULARITY]


# --- Way 2: Lambda (shorthand for the same thing) ---
get_popularity_lambda = lambda act: act[POPULARITY]

# Prove they're identical:
test_act = ("Bad Bunny", "9:00 PM", 98, "reggaeton", "Main")
print(f"Regular function: {get_popularity(test_act)}")
print(f"Lambda function:  {get_popularity_lambda(test_act)}")

# The real payoff — both work the same way with sorted():
sorted_with_def = sorted(lineup, key=get_popularity)
sorted_with_lambda = sorted(lineup, key=lambda act: act[POPULARITY])

print(f"\nSame result? {sorted_with_def == sorted_with_lambda}")
print(f"Least popular: {sorted_with_def[0][ARTIST]}")

# We use lambda because writing a whole def for one quick line feels like overkill.
# Think of it as: def is a full sentence, lambda is a sticky note.

Reading the lambda syntax

# lambda act: act[POPULARITY]
#   ^      ^    ^
#   |      |    |__ what to return
#   |      |__ the input (like a parameter)
#   |__ keyword that says "this is a mini function"

Read lambda act: act[POPULARITY] as: "a mini function that takes an act and returns its popularity."

In [ ]:
# More lambda examples — each extracts a different field
get_name = lambda act: act[ARTIST]
get_stage = lambda act: act[STAGE]
is_popular = lambda act: act[POPULARITY] >= 85

print(get_name(lineup[0]))       # "Bad Bunny"
print(get_stage(lineup[0]))      # "Main"
print(is_popular(lineup[0]))     # True

You don't need to fully master lambda right now. Just remember: when you see key=lambda act: act[POPULARITY] in sorted(), it means "sort by this field."

sort() vs sorted()

In [ ]:
# .sort() modifies the list IN PLACE (returns None!)
# sorted() creates a NEW sorted list (original unchanged)

# Simple example first
numbers = [3, 1, 4, 1, 5, 9, 2, 6]

sorted_numbers = sorted(numbers)
print(f"Original:      {numbers}")
print(f"sorted() gave: {sorted_numbers}")

numbers.sort()
print(f"After .sort(): {numbers}")  # Original is now changed!
In [ ]:
# To sort our lineup by popularity, we need key= to tell Python which field

by_popularity = sorted(lineup, key=lambda act: act[POPULARITY])
print("Least to most popular:")
for act in by_popularity[:5]:
    print(f"  {act[ARTIST]}: {act[POPULARITY]}")

# Reverse for most popular first
by_popularity_desc = sorted(lineup, key=lambda act: act[POPULARITY], reverse=True)
print("\nMost to least popular:")
for act in by_popularity_desc[:5]:
    print(f"  {act[ARTIST]}: {act[POPULARITY]}")
In [ ]:
# Sorting by artist name (alphabetical)
alphabetical = sorted(lineup, key=lambda act: act[ARTIST])
print("Alphabetical lineup:")
for act in alphabetical[:5]:
    print(f"  {act[ARTIST]}")

5. Copying — The Aliasing Bug

Before we practice sorting, there's a dangerous trap you need to know about. What happens when you write list_b = list_a?

In [ ]:
# WARNING: This does NOT copy the list!
original = [1, 2, 3, 4, 5]
alias = original  # This just creates a second NAME for the same list

alias.append(99)
print(f"alias:    {alias}")
print(f"original: {original}")  # 99 is here too!
print(f"Same object? {alias is original}")  # True!
In [ ]:
# Two ways to make a REAL copy:
original = [1, 2, 3, 4, 5]

copy_1 = original.copy()   # Method 1: .copy()
copy_2 = original[:]       # Method 2: slice the whole list

copy_1.append(99)
copy_2.append(77)

print(f"original: {original}")  # Unchanged!
print(f"copy_1:   {copy_1}")
print(f"copy_2:   {copy_2}")
In [ ]:
# Why this matters: sorting without destroying the original
# sorted() already returns a new list, so it's safe:
sorted_by_pop = sorted(lineup, key=lambda act: act[POPULARITY], reverse=True)

print(f"Original first act: {lineup[0][ARTIST]}")         # Bad Bunny — unchanged
print(f"Sorted first act:   {sorted_by_pop[0][ARTIST]}")  # Bad Bunny — highest popularity

Quick reference:

Code What it does
b = a Creates an alias — both names point to the same list
b = a.copy() Creates a real copy — independent lists
b = a[:] Also creates a real copy — slicing the whole list
b = sorted(a) Creates a new sorted list — a is unchanged
a.sort() Sorts a in place — original order is lost

For lists of simple values or tuples, .copy() and [:] work perfectly. If you ever have lists inside lists and need fully independent copies, Python has copy.deepcopy() — but you won't need that in this course.


Question 3: Sort Without Mutating (1 point)

Create a sorted version of the festival lineup ranked by popularity (highest first) without changing the original lineup.

Store the sorted list in popularity_ranking. Then extract just the artist name of the most popular act into most_popular_artist and the least popular act into least_popular_artist.

Hint: Use sorted() with key=lambda act: act[POPULARITY] and reverse=True. The most popular is the first item, the least popular is the last (index -1).

In [ ]:
# ✏️ YOUR CODE HERE
popularity_ranking = ...
most_popular_artist = ...
least_popular_artist = ...

print(f"Most popular: {most_popular_artist}")
print(f"Least popular: {least_popular_artist}")
print(f"\nOriginal lineup still intact? First act: {lineup[0][ARTIST]}")
In [ ]:
grader.check("q3_sorted_lineup")

Day 2: List Comprehension & Aggregates

Quick recap from Day 1:

  • Slicing: list[start:stop:step] — creates a new list, never mutates
  • insert(i, item): adds at position, shifts others right — mutates
  • pop(i): removes and returns item at position — mutates
  • sorted(list, key=, reverse=): returns new sorted list — no mutation
  • .sort(): sorts in place — mutates
  • .copy() or [:]: make a real copy to avoid aliasing bugs
  • lambda: a mini one-line function, used with key= to tell sorted() which field to sort by

Now let's learn aggregates and list comprehension — powerful tools for building new lists in a single line.


6. Aggregate Functions

Python has built-in functions that summarize a whole list into a single value. These replace the manual accumulator and max-tracking loops you wrote in Lecture 05.

In [ ]:
# Python has built-in functions for common list calculations
# (Don't worry about the [...] syntax yet — we'll learn it in the next section!)
scores = [act[POPULARITY] for act in lineup]

print(f"All scores: {scores}")
print(f"Total popularity: {sum(scores)}")
print(f"Highest: {max(scores)}")
print(f"Lowest: {min(scores)}")
print(f"Number of acts: {len(lineup)}")
print(f"Average: {sum(scores) / len(scores):.1f}")
In [ ]:
# max() and min() work on tuples too, with key=
most_popular_act = max(lineup, key=lambda act: act[POPULARITY])
least_popular_act = min(lineup, key=lambda act: act[POPULARITY])

print(f"Most popular: {most_popular_act[ARTIST]} ({most_popular_act[POPULARITY]})")
print(f"Least popular: {least_popular_act[ARTIST]} ({least_popular_act[POPULARITY]})")

Connection to Lecture 05: These aggregates replace the manual loop patterns you wrote for Spotify data. sum() replaces your accumulator loop. max() with key= replaces the track-best-so-far loop. Same results, less code.


7. List Comprehension — Transformation

List comprehension creates a new list by transforming each item from an existing list. It's a shortcut for the "create empty list → loop → append" pattern you've been using since Lecture 05.

Reading the syntax

# [act[ARTIST] for act in lineup]
#  ^            ^   ^    ^
#  |            |   |    |__ the list to loop over
#  |            |   |__ each item, one at a time
#  |            |__ keyword that starts the loop
#  |__ what to put in the new list (the transformation)
In [ ]:
# List comprehension creates a NEW list by transforming each item

# Old way (from Lecture 05):
artist_names_old = []
for act in lineup:
    artist_names_old.append(act[ARTIST])
print(f"Old way: {artist_names_old[:5]}")

# New way — list comprehension (same result, one line!):
artist_names = [act[ARTIST] for act in lineup]
print(f"New way: {artist_names[:5]}")
In [ ]:
# More transformations

# Uppercase all artist names
upper_names = [act[ARTIST].upper() for act in lineup]
print(f"Uppercase: {upper_names[:5]}")

# Build formatted schedule strings
schedule_cards = [f"{act[ARTIST]} @ {act[TIME_SLOT]} ({act[STAGE]} Stage)" for act in lineup]
print("\nSchedule cards:")
for card in schedule_cards[:5]:
    print(f"  {card}")

# Extract just popularity scores
all_scores = [act[POPULARITY] for act in lineup]
print(f"\nScores: {all_scores}")
In [ ]:
# Side by side — same result, different style

# Loop version (3 lines):
doubled_loop = []
for act in lineup:
    doubled_loop.append(act[POPULARITY] * 2)

# Comprehension version (1 line):
doubled_comp = [act[POPULARITY] * 2 for act in lineup]

print(f"Loop version: {doubled_loop[:5]}")
print(f"Comp version: {doubled_comp[:5]}")
print(f"Same result?  {doubled_loop == doubled_comp}")

Key point: List comprehension is a shortcut for the "create empty list, loop, append" pattern. Same result, one line instead of three. Use it when the transformation is simple enough to read in one line.


Question 4: Transformation Comprehension (1 point)

Use list comprehension to build two new lists from the lineup.

First, create act_summaries — a list of formatted strings where each entry looks like 'Bad Bunny (98)' (artist name followed by their popularity score in parentheses).

Second, create popularity_doubled — a list of integers where each popularity score is doubled.

Hint: For act_summaries, use an f-string as the expression: f"{act[ARTIST]} ({act[POPULARITY]})"

In [ ]:
# ✏️ YOUR CODE HERE
act_summaries = ...
popularity_doubled = ...

print("Act summaries:")
for summary in act_summaries[:5]:
    print(f"  {summary}")
print(f"\nDoubled scores: {popularity_doubled[:5]}")
In [ ]:
grader.check("q4_transform")

8. List Comprehension — Filtering

Add an if clause to filter which items are included in the new list. Only items where the condition is True make it into the result.

In [ ]:
# Add an if clause to FILTER which items are included
# Syntax: [expression for item in list if condition]

# Old way:
pop_acts_old = []
for act in lineup:
    if act[GENRE] == "pop":
        pop_acts_old.append(act)

# New way:
pop_acts = [act for act in lineup if act[GENRE] == "pop"]

print(f"Pop acts ({len(pop_acts)}):")
for act in pop_acts:
    print(f"  {act[ARTIST]} — {act[STAGE]} Stage")
In [ ]:
# More filtering examples

# Acts on the Main stage
main_stage = [act for act in lineup if act[STAGE] == "Main"]
print(f"Main stage acts: {len(main_stage)}")

# High-popularity acts (85+)
headliner_tier = [act for act in lineup if act[POPULARITY] >= 85]
print(f"Headliner tier (85+ popularity): {[act[ARTIST] for act in headliner_tier]}")

# Non-pop acts
non_pop = [act for act in lineup if act[GENRE] != "pop"]
print(f"Non-pop acts: {len(non_pop)}")

Question 5: Filtering Comprehension (1 point)

Use list comprehension to create filtered lists from the lineup.

First, create hip_hop_acts containing only the acts whose genre is 'hip-hop'.

Second, create prime_time_names — a list of just the artist NAMES (strings, not tuples) for acts performing on the 'Main' stage with a popularity score of 90 or above.

Hint: For prime_time_names, combine a transformation (act[ARTIST]) with a filter (if act[STAGE] == "Main" and act[POPULARITY] >= 90) in the same comprehension.

In [ ]:
# ✏️ YOUR CODE HERE
hip_hop_acts = ...
prime_time_names = ...

print(f"Hip-hop acts ({len(hip_hop_acts)}):")
for act in hip_hop_acts:
    print(f"  {act[ARTIST]}")
print(f"\nPrime time headliners: {prime_time_names}")
In [ ]:
grader.check("q5_filter")

9. Combined Comprehension — Filter + Transform

You can filter and transform in the same comprehension. This is the full power of the syntax.

Reading the combined syntax

# [act[ARTIST] for act in lineup if act[GENRE] == "pop"]
#  ^            ^   ^    ^       ^
#  |            |   |    |       |__ only include items where this is True
#  |            |   |    |__ the list to loop over
#  |            |   |__ each item, one at a time
#  |            |__ keyword that starts the loop
#  |__ what to put in the new list
In [ ]:
# Filter AND transform in the same comprehension

# Get formatted cards for only Coral stage acts
coral_cards = [
    f"{act[ARTIST]} @ {act[TIME_SLOT]}"
    for act in lineup
    if act[STAGE] == "Coral"
]
print("Coral Stage Schedule:")
for card in coral_cards:
    print(f"  {card}")
In [ ]:
# Combine comprehension with aggregate functions
pop_acts_list = [act for act in lineup if act[GENRE] == "pop"]
pop_avg = sum(act[POPULARITY] for act in pop_acts_list) / len(pop_acts_list)
print(f"Average pop act popularity: {pop_avg:.1f}")

# Most popular hip-hop act
hh_acts = [act for act in lineup if act[GENRE] == "hip-hop"]
top_hh = max(hh_acts, key=lambda act: act[POPULARITY])
print(f"Top hip-hop act: {top_hh[ARTIST]} ({top_hh[POPULARITY]})")

Stretch Goal: VIP Schedule (1 bonus point)

Build a VIP schedule card list. Use a single list comprehension to create vip_schedule — a list of formatted strings in the format 'ARTIST @ TIME (STAGE Stage)' but only for acts with a popularity of 85 or higher.

Then use sum() with a comprehension to calculate vip_total_popularity — the total popularity score of all acts in the VIP tier (85+).

Hint: Combine what you learned in Q4 (transformation) and Q5 (filtering) into one comprehension. For the sum, you can use sum(expression for item in list if condition) directly.

In [ ]:
# ✏️ YOUR CODE HERE
vip_schedule = ...
vip_total_popularity = ...

print(f"VIP Schedule ({len(vip_schedule)} acts):")
for card in vip_schedule:
    print(f"  {card}")
print(f"\nTotal VIP popularity: {vip_total_popularity}")
In [ ]:
grader.check("q6_stretch_combined")

Summary

Congratulations! You've learned how to manipulate lists like a pro for CanesFest 2026!

Concept Syntax Festival Example
Slice list[start:stop:step] lineup[:5] (headliners)
Reverse slice list[::-1] lineup[::-1] (reversed order)
String slice str[start:stop] "CanesFest"[:5]
Insert list.insert(i, item) Add surprise guest at position 2
Pop list.pop(i) Remove cancelled act
Lambda lambda x: x[FIELD] Mini function for sort key
sorted() sorted(list, key=, reverse=) Rank by popularity
.sort() list.sort() Sort in place (mutates!)
Copy list.copy() or list[:] Sort a copy, keep original
sum/min/max sum(list), min(), max() Total/highest popularity
Transform comprehension [expr for x in list] [act[ARTIST] for act in lineup]
Filter comprehension [x for x in list if cond] [act for act in lineup if act[GENRE] == "pop"]
Combined [expr for x in list if cond] VIP schedule cards

Key Takeaways

  1. Slicing creates new lists — never mutates the original
  2. insert() and pop() mutate — know which operations change your list
  3. lambda is a mini function — read lambda act: act[POPULARITY] as "given an act, return its popularity"
  4. Use sorted() over .sort() when you need the original order preserved
  5. list_b = list_a is aliasing, not copying — use .copy() or [:]
  6. List comprehension replaces the empty-list, loop, append pattern in one line
  7. Filter + transform in one comprehension: [expr for x in list if cond]

What's Next?

  • Lab: Project 1 — Budget Analyzer (apply list operations to real financial data)
  • Next Lecture: Dictionaries and Sets — key-value pairs and unique collections

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/lecture_notebooks/08_lecture_advanced_lists/08_lecture_advanced_lists.ipynb
    • Windows: Open File Explorer → Documents\CSC115\lecture_notebooks\08_lecture_advanced_lists\08_lecture_advanced_lists.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 08_lecture_advanced_lists.ipynb

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


You have completed the Advanced List Operations notebook.


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

In [ ]:
grader.check_all()