Lists (1-D arrays)
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A list holds many values
- A list keeps many values in one variable.
- Write the items inside square brackets:
[10, 20, 30]. - The items can be numbers, strings, or a mix.
Get and change items
- Use an index, just like a string:
nums[0]is the first item. nums[-1]is the last item.- You can also change an item:
nums[0] = 99.
fruits = ["apple", "pear", "plum"]
print(fruits[0])
print(fruits[-1])
Add items and count them
nums.append(x)addsxto the end of the list.len(nums)tells you how many items there are.- A list can grow as your program runs.
fruits = ["apple", "pear"]
fruits.append("plum")
print(len(fruits))
print(fruits)
Loop over a list
for item in nums:visits each item in turn.- The loop variable holds one item per pass.
- This is the easy way to process every value.
scores = [10, 20, 30]
total = 0
for s in scores:
total = total + s
print(total)
In Cambridge pseudocode
- A list is the exam's 1-D array. Note: exam arrays often start at index
1, but Python lists start at0.
DECLARE scores : ARRAY[1:3] OF INTEGER
scores[1] ← 10
scores[2] ← 20
scores[3] ← 30
FOR i ← 1 TO 3
OUTPUT scores[i]
NEXT i
Now you try
- Build or loop over a list in each task.
- Press Check answer to test your code.
Create a list colors holding "red", "green", "blue". Then append "yellow" so the list has four items.
Click Run to see the output here.
Loop over the list nums and add up its values. Store the total in total (the answer is 66).
Click Run to see the output here.
Find the largest value in nums with a loop. Start largest at the first item, then loop through nums and keep the bigger value. Store the answer in largest (it is 23).
Click Run to see the output here.