A list isn’t fixed. You can add to it, remove from it, and ask how long it is — and the most useful move of all is building a list up from nothing inside a loop.
Same chapter as 3.6 — today it’s the methods that change a list. Enrolled in our Runestone course? Open it from there so your progress counts.
Still in Programs. In 3.6 a list held a fixed set of values. Today it becomes dynamic — and you meet the pattern where an accumulator (3.4) builds a list instead of a number.
Programs do the same: start with an empty list, then
append to it inside a loop as data arrives. That “empty list plus a loop that
adds” is one of the most common shapes in all of programming.
A handful of operations change a list. Here are the four you need, in both notations:
| Do this | Python | AP Pseudocode |
|---|---|---|
| add to the end | nums.append(7) | APPEND(nums, 7) |
| insert at a position | nums.insert(0, 7) | INSERT(nums, 1, 7) |
| remove a position | nums.pop(2) | REMOVE(nums, 3) |
| how many elements | len(nums) | LENGTH(nums) |
len() / LENGTH() is the honest count of elements — and it’s
how you avoid the index flip biting you. The last valid Python index is always
len(nums) - 1; in AP it’s simply LENGTH(nums). Reach past that and
you get an error.
nums = [] # start empty for i in range(3): x = int(input("num? ")) nums.append(x) # grow it print(nums) # all three
# the accumulator — but a list, # not a number # read one value per pass # append = the "update" step # use the finished list after
Hover or tap a line to light its twin. This is the accumulator pattern from 3.4 with a list in the accumulator’s seat: initialize empty, append inside, use after.
Add values to the end, remove the last one, and watch the length update. This is
append, pop, and len in action.
append / APPEND).len() / LENGTH()). The last Python
index is len - 1.No brand-new Big Ideas today — this is a fluency day. The goal is speed and confidence with list operations.
Five questions. Track the list step by step as it changes, then pick your answer.
Every feed you scroll was built this way: start empty, loop over incoming posts, append each one. Every “add to cart,” every uploaded photo joining an album, every new message landing in a thread — an append to a growing list. It’s the shape of software that collects.
And len() is quietly everywhere too: the little number badge
on your notifications, “3 items in cart,” “127 unread” — that’s
just the length of a list, read out loud.