Grade 9 Computer Science — Building a list as you go
Start from an empty list and add to it inside a loop, and work out how many values end up in it and what sits at each position.
Name: ________________________
1.Look hard at the range before working anything else out. How many values does this list end up with?
empty = [] for n in range(5, 5): empty.append(n) print(len(empty))2.A running total is appended each time round here, so the list holds the totals rather than the values. What does the program print?
totals = [] running = 0 for n in range(1, 5): running = running + n totals.append(running) print(totals[3])3.The test in this one is about the counter doubled rather than the counter itself. How many values does the list end up with?
evens = [] for n in range(0, 12): if n * 2 < 10: evens.append(n) print(len(evens))4.This program starts with an empty list and puts one value into it each time round. How many values does it end up with?
squares = [] for n in range(1, 5): squares.append(n * n) print(len(squares))5.One loop sits inside another here, and the appending is in the deeper of the two. What does the program print?
pairs = [] for a in range(0, 3): for b in range(0, 4): pairs.append(a + b) print(len(pairs))- a) 4
- b) 3
- c) 7
- d) 12
6.Work out what this program prints. The values are not the counter itself this time.
doubles = [] for n in range(3, 7): doubles.append(n * 2) print(doubles[2])7.There are two appends inside this loop rather than one. How many values does the list end up with?
names = [] for n in range(1, 4): names.append(n) names.append(n * 10) print(len(names))8.Only some of the counter's values get into this list. What does the program print?
found = [] for n in range(1, 8): if n * n > 20: found.append(n) print(found[0])- a) 25
- b) 4
- c) 6
- d) 5
Answer key — Grade 9 Computer Science — Building a list as you go
- 1.
- 0
- none
- nought
- 2. 10
- 3. 5
- 4. 4
- 5. d) 12
- 6. 10
- 7. 6
- 8. d) 5