Big Idea 3.10: Lists

Shoreline Community Services logo

Theme: Shoreline Outreach. Every list, count, and average in this unit uses real-style data from Shoreline Community Services’ volunteer and donation programs.

Shoreline Community Services supports unsheltered individuals and families in San Diego’s Central Beach Area through volunteer-run outreach, donation drives, and direct aid. This lesson borrows its examples from that kind of work so the practice feels grounded in something real.

Three short lessons, each with a 5 minute Popcorn Hack you do in class. One 10 minute Homework Hack at the end pulls all three together, graded as a single point.

Lesson Topic Popcorn Hack (5 min)
1 What lists are, creating, indexing Four supply items, predict the output
2 Sum and average Live volunteer-hours accumulator
3 Counting frequencies and filtering Class donation-item survey

1. LxD Cycle Process

Empathize: Students coming from single value variables write score1, score2, score3 and then cannot loop over them. They assume the first item sits at position 1, they forget to initialize total = 0, and they try to count categories with a pile of separate counter variables.

Define:

  • POV: CSP students need lists, the accumulator pattern, and dictionaries because separate variables cannot be looped, counted, or grown, and because none of them scale to data you have not seen in advance.
  • Learning Goal: Students will create and index lists, total and average them with an explicit loop, and count and filter them.

Ideate:

  • HMW Question: How might we make a silent wrong answer as visible as a crash?
  • Activity: Three short predict then run activities, each with a deliberate failure the class has to fix.

Prototype and Test: Run the three Popcorn Hacks live and watch whether students predict each crash correctly before they execute the cell — that is the real signal for whether the HMW question is answered. If most predictions miss the crash, tighten the indexing and empty-list warnings in the Tech Talk before moving on.


2. Lesson Plan

Learning Objective: By the end of these three lessons, you will be able to create a list, access any element by index, total and average a numeric list with a loop, count how often each value appears, and filter a list by a condition.

Success Criteria: Given any list, you can state its length, name the index of the first and last elements, produce a correct total and average without crashing on an empty list, and build a frequency count and a filtered list without altering the original.

[!IMPORTANT] Submission rules for every hack in this unit:

  • Python only, and keep the # CODE_RUNNER comment line at the top of each cell.
  • Use loops, not list comprehensions. AP pseudocode maps to explicit loops.
  • Run every cell and confirm the printed output before submitting.
  • Print your results. A cell with no output scores zero.

3. Reference Guide

From the College Board

AP CSP Big Idea 3: Algorithms and Programming, Topic 3.10 Lists (Learning Objective AAP-1.G, “Explain how the use of lists can simplify the solution of a problem”).

[!NOTE] The bullets below paraphrase the AP CSP Course and Exam Description’s Essential Knowledge for this topic rather than quoting exact page numbers, since we are working from the pseudocode reference sheet, not a page-numbered copy of the CED. Check your own CED copy if you need an exact citation.

  • A list is a data structure that stores an ordered sequence of elements, referenced by a single name, that can be accessed using an index.
  • In AP CSP pseudocode (not Python), the first element of a list is at index 1, not 0. This is different from Python, where indexing starts at 0 — a common point of confusion on the exam.
  • The reference pseudocode defines four list operations you are expected to know: APPEND(list, value), INSERT(list, index, value), REMOVE(list, index), and LENGTH(list).
  • Iterating over every element of a list uses FOR EACH item IN list { ... }.
  • The official pseudocode reference sheet does not define a dictionary/map data structure — only lists. Where this lesson uses frequency[season]-style bracket access for counting, that is an informal extension by analogy to list indexing, not standard AP CSP pseudocode.

Key Vocabulary

Term Definition Example
List One variable holding an ordered collection of values. ages = [15, 16, 17]
Index A position number used to access an element. ages[0]
Element A single value stored inside a list. 16 in ages
Accumulator A variable that collects a running total across a loop. total = 0
Dictionary A Python lookup table of key/value pairs, used here for counting. frequency = {}
Filter Building a new list that only keeps items passing a condition. adults = []

Python vs. AP CSP Pseudocode

Concept Python AP CSP Pseudocode
First index list[0] list[1]
Add to end list.append(x) APPEND(list, x)
Insert at position list.insert(i, x) INSERT(list, i, x)
Remove at position del list[i] REMOVE(list, i)
Length len(list) LENGTH(list)
Loop over items for x in list: FOR EACH x IN list { }
Assignment x = 5 x ← 5

Picking the Right Pattern

  • Need every value, in order, once? → Accumulator loop (Lesson 2).
  • Need to know how often something repeats? → Frequency dictionary (Lesson 3).
  • Need a subset that matches a rule? → Filter into a new list (Lesson 3).

4. Lessons & Practice

Lesson 1: What Is a List?

Tech Talk (3 minutes)

A list is one variable holding an ordered collection of values.

  • Ordered: elements keep their position.
  • Indexed: positions start at 0 in Python (but 1 in AP CSP pseudocode — see the Reference Guide above).
  • Mutable: you can change, add, and remove elements.
  • Duplicates allowed: the same value can appear many times.

The last valid Python index is always len(list) - 1. Asking for len(list) itself is the most common list error in CSP.

Code Examples

A. Simple: Creating Lists

# List of integers
meals_served = [15, 16, 17, 15, 16]

# List of strings
supplies = ["blankets", "socks", "water", "blankets"]

# List of mixed types
donation = [50, "Jordan", 12.5, True]

print(meals_served)
print(supplies)
print(donation)

B. Intermediate: Accessing Elements

needs = ["blankets", "socks", "water", "meals"]

print(needs[0])    # blankets - first element
print(needs[2])    # water    - third element
print(needs[-1])   # meals    - last element
print(len(needs))  # 4        - how many elements

C. Complex: Changing a List

shifts = ["intake", "sorting", "delivery"]

shifts[1] = "packing"        # replace by index
shifts.append("checkin")     # add to the end
shifts.remove("delivery")    # remove by value

print(shifts)                # ['intake', 'packing', 'checkin']

for i in range(len(shifts)):
    print(i, shifts[i])

Popcorn Hack (5 minutes)

[!TIP] Predict first, then run. Paste your four line prediction in chat before you execute the cell.

Task: Predict the output of all four print statements, then run the cell and fix the one that breaks. Compare against the AP CSP pseudocode reference below it — notice the last valid index shifts from 3 to 4 once you switch to 1-indexing.

AP CSP Pseudocode (reference):

items_needed ← ["blankets", "socks", "water", "meals"]

DISPLAY(items_needed[1])
DISPLAY(items_needed[LENGTH(items_needed)])
DISPLAY(LENGTH(items_needed))
DISPLAY(items_needed[5])

Code Runner Challenge

Lists Popcorn 1 - predict, run, fix the crash

View IPYNB Source
# CODE_RUNNER: Lists Popcorn 1 - predict, run, fix the crash
#Convert the above CollegeBoard Psuedocode into Python code and run it.
#Predict the output of each print statement before running the code. Add your prediction as a comment next to each print statement.

items_needed = ["blankets", "socks", "water", "meals"]
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Part 2 You may have noticed that one of the commands gave you an Index Error. Try fixing the error and place it in your code. Expected direction: the first three print the first item, the last item, and 4. The fourth raises IndexError in Python because valid indexes are 0 through 3 — fix it to items_needed[3]. In the pseudocode version, valid indexes are 1 through 4, so the equivalent fix is items_needed[4].


Lesson 2: Sum and Average

Tech Talk (3 minutes)

The accumulator pattern has three parts and they must happen in this order.

  1. Initialize a running total to 0 before the loop.
  2. Add each element to the total inside the loop.
  3. Use the total after the loop finishes.

Average is total / len(list). Two traps:

  • Initializing total inside the loop resets it every pass.
  • Dividing by len(list) when the list is empty raises ZeroDivisionError.

Code Examples

A. Simple: Sum

donations = [78, 85, 92, 88, 95]

total = 0
for donation in donations:
    total += donation

print(f"Total donations: {total}")   # Total donations: 438

B. Intermediate: Average with Rounding

donations = [78, 85, 92, 88, 95]

total = 0
for donation in donations:
    total += donation

average = total / len(donations)
print(f"Average donation: {round(average, 2)}")   # Average donation: 87.6

Popcorn Hack (5 minutes)

[!TIP] Live data. Six students call out one number each, then everyone uses the same list.

Task: After learning how the accumulator pattern works, students should be able to build loops of their own to calculate the sum and average of a set of given numbers

Code Runner Challenge

Lists Popcorn 2

View IPYNB Source
# CODE_RUNNER: Lists Popcorn 2
#Now try it yourself! Write a for loop that calculates the sum of all the volunteer hours in the list and prints it out.
#Calculate the average of the volunteer hours in the list using the value you calculated for the sum and the length of the list and print it out.

volunteer_hours = [7, 6, 8, 5, 7, 9]
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Expected direction: total 42, average 7.0. On the empty list the Python cell raises ZeroDivisionError. Add an if len(volunteer_hours) == 0: guard that prints "No data yet" instead.


Lesson 3: Counting Frequencies and Filtering

Tech Talk (3 minutes)

Two patterns, both built on a single loop.

Frequency counting uses one dictionary for any number of categories.

  • Start with an empty dictionary.
  • For each item: if the key already exists, add 1. Otherwise set it to 1.

Filtering builds one new list and leaves the original untouched.

  • Start with an empty list.
  • For each item: if the condition is true, append() it to the new list.

Never remove items from a list while looping over it. Build a new one instead.

Code Examples

A. Simple: Frequency Count

donations = ["blankets", "socks", "meals", "socks", "socks", "water", "meals"]

frequency = {}
for item in donations:
    if item in frequency:
        frequency[item] += 1
    else:
        frequency[item] = 1

print(frequency)
# {'blankets': 1, 'socks': 3, 'meals': 2, 'water': 1}

B. Intermediate: Filtering

donation_amounts = [12, 18, 15, 21, 17, 25, 14, 19]

big_donations = []
for amount in donation_amounts:
    if amount >= 18:
        big_donations.append(amount)

print(big_donations)      # [18, 21, 25, 19]
print(donation_amounts)   # original unchanged

C. Complex: Count, Then Filter the Counts

donations = ["blankets", "socks", "meals", "socks", "socks", "water", "meals"]

frequency = {}
for item in donations:
    if item in frequency:
        frequency[item] += 1
    else:
        frequency[item] = 1

popular = []
for item in frequency:
    if frequency[item] >= 2:
        popular.append(item)

print(popular)   # ['socks', 'meals']

Popcorn Hack (5 minutes)

[!TIP] Live survey. Everyone types an item they would donate in chat, then build the list from the real responses.

Task: Count the class responses, then filter to the items with two or more votes. The frequency count is scaffolded below; you write the filter. Remember: the pseudocode version’s frequency[item] bracket notation is an informal extension, not official AP CSP syntax (see the College Board section above).

Code Runner Challenge

Lists Popcorn 3 - count then filter

View IPYNB Source
# CODE_RUNNER: Lists Popcorn 3 - count then filter

items_requested = ["blankets", "socks", "meals", "socks", "water", "socks", "meals"]   # use real class data

frequency = {}
for item in items_requested:
    if item in frequency:
        frequency[item] += 1
    else:
        frequency[item] = 1


# 1. Build a list of items with 2 or more votes
# TODO: create an empty list called popular, loop over frequency,
# and append any item whose count is 2 or more

# 2. Print that list
# TODO: print(popular)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

AP CSP Pseudocode (reference):

items_requested ← ["blankets", "socks", "meals", "socks", "water", "socks", "meals"]

frequency ← {}
FOR EACH item IN items_requested
{
  IF (item IS IN frequency)
  {
    frequency[item] ← frequency[item] + 1
  }
  ELSE
  {
    frequency[item] ← 1
  }
}

DISPLAY(frequency)

// TODO: create an empty list called popular, loop over frequency,
// and append any item whose count is 2 or more

Expected direction: the dictionary has one key per unique item and the counts add up to the number of students. The filtered list is shorter than the number of unique items unless every item got two votes.


5. Homework Task (10 minutes)

This is the only homework for the unit. It uses all three lessons on one dataset: item donations from a supply drive and what each one costs to source.

Code Runner Challenge

Lists Homework - indexing, accumulator, count and filter on one dataset

View IPYNB Source
# CODE_RUNNER: Lists Homework - indexing, accumulator, count and filter on one dataset

donations_by_item = ["blankets", "socks", "blankets", "water", "socks", "blankets",
                      "meals", "socks", "blankets", "water", "blankets", "socks"]

costs = [2, 3, 2, 4, 3, 2, 1, 3, 2, 4, 2, 3]

# LESSON 1 - indexing
# 1. Print how many donations were made
# 2. Print the last donation using indexing

# LESSON 2 - sum and average
# 3. Use a loop to total costs (do NOT use sum())
# 4. Print "Total: <total>" and "Average: <average>" as integers using the int() function
#ex: print(int(total)) would print the integer value of total

# LESSON 3 - count and filter
# 5. Build a frequency dictionary of donations_by_item and print it
# 6. Build a list of items with 3 or more donations and print it
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Expected output shape:

12
socks
Total: 31
Average: 2
{'blankets': 5, 'socks': 4, 'water': 2, 'meals': 1}
['blankets', 'socks']

Add This Lesson to Your Portfolio

Once your homework is done, save it to your own portfolio.

  • Open your Portfolio repo (the one you publish with GitHub Pages).
  • In the _notebooks folder, create a new file named YYYY-MM-DD-lists.ipynb, using today’s date.
  • Make the first cell a Raw cell and give it front matter:
    ---
    layout: post
    title: 3.10 Lists
    permalink: /csp/big-idea-3/lists/
    toc: true
    comments: false
    ---
    
  • Add a markdown cell with a ## Lists heading, then copy each completed Popcorn Hack and the Homework Hack into their own code cells.
  • Commit and push your changes: git add ., git commit -m "Add Lists lesson", git push.
  • Confirm your page builds by visiting your portfolio site at the permalink above.

6. Grading Plan (1 Point Total)

Classroom Rubric

  • 0.3 points: Popcorn completion. 0.1 for each of the three in class hacks, submitted as a runnable cell with the fix applied.
  • 0.7 points: Homework completion.
    • 0.15 indexing: correct len() and a last element found with [-1] or len(donations_by_item) - 1, not a hardcoded number.
    • 0.2 accumulator: total initialized to 0 before the loop, added to inside it, and divided correctly with int().
    • 0.2 frequency dictionary: correct counts for all four donation types using the if and else key pattern.
    • 0.15 filtering: new list built with append(), threshold applied correctly, and donations_by_item left unmodified.

Quick Validation Checklist

  • Present: the # CODE_RUNNER comment line.
  • Present: total = 0 on a line before the for, an empty {} before the counting loop, and an empty [] before the filter loop.
  • Absent: sum(), list comprehensions, and any hardcoded index in step 2.
  • Present: all six printed lines matching the expected output shape.

Common Problems to Avoid

  • Off by one errors. Python indexing starts at 0; AP CSP pseudocode indexing starts at 1.
  • Index out of range. Do not access list[5] if the list has only 4 elements.
  • Modifying a list while iterating over it. Build a new list instead.
  • Forgetting to initialize variables. Set total = 0 before summing.
  • Use descriptive names like student_names instead of list1.
  • Check for empty lists before accessing elements or dividing.
  • Test edge cases: empty lists, single elements, all the same value.

Summary

Lists store and organize collections of data. Across these three lessons you learned to access elements by index (in both Python and AP CSP pseudocode), compute a sum and an average with an accumulator loop, count the frequency of items with a dictionary, filter a list based on a condition, and guard against empty lists and out of range indexes.

Submit Assignment

Click to upload or drag and drop
PDF, ZIP, images, documents, or Jupyter notebooks (.ipynb) (Max 10MB per file)

Need to update a submission later? Open the submissions dashboard.