Lists and data abstraction
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Why a list?
- A program often needs many values at once, like a class of scores.
- One variable per value would be messy.
- A list holds many values under one name — a useful data abstraction.
What is a data abstraction?
- An abstraction hides detail so you can think about the whole, not the parts.
- A list lets you treat 1 value or 1000 values the same way.
- You write the same code no matter how long the list is.
Make a list and read it
- Write items inside square brackets:
[10, 20, 30]. - Get one item by its index (its position). Python starts at
0. scores[0]is the first item;scores[-1]is the last item.
scores = [10, 20, 30]
print(scores[0])
print(scores[-1])
print(len(scores))
Grow a list with append
scores.append(x)addsxto the end of the list.- The list can grow while the program runs.
len(scores)tells you how many items it now has.
scores = [10, 20]
scores.append(30)
print(scores)
print(len(scores))
Traverse (visit every item)
- To traverse a list means to go through every item, one by one.
for s in scores:gives you one item each pass — this is a for-each loop.- It is the clean way to process the whole list.
scores = [10, 20, 30]
total = 0
for s in scores:
total = total + s
print(total)
In AP CSP pseudocode
- A list is the exam's list too — but CB lists are 1-indexed.
- So
aList[1]is the first element in CB, while Python's first isscores[0]. FOR EACH x IN listmatches Python'sfor x in list:.DISPLAY= print,←==.
aList ← [10, 20, 30]
DISPLAY aList[1] ## the FIRST item (1-indexed!)
total ← 0
FOR EACH x IN aList
{
total ← total + x
}
DISPLAY total
Now you try
- Build, grow, or traverse a list in each task.
- Press Check answer to test your code.
Start from the list colors = ["red", "green"]. Use .append(...) to add "blue" to the end, so the list becomes ["red", "green", "blue"].
Click Run to see the output here.
nums is [4, 8, 15, 16, 23]. Traverse it with a for loop to add up every value, then print the total. (It should print 66.)
Click Run to see the output here.
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]. Store the first day in first and the last day in last using indexing.
Click Run to see the output here.