Class 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.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) 5
- b) 6
- c) 25
- d) 4
2.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) 3
- b) 4
- c) 12
- d) 7
3.This program appends four values. Put them in the order they end up sitting in the list, the front of the list first.
made = [] for n in range(2, 6): made.append(n * n)- 9
- 25
- 16
- 4
4.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))5.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))6.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])7.This one prints the value that ended up at the front of the list. What does it print?
squares = [] for n in range(1, 6): squares.append(n * n) print(squares[0])8.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))
Answer key — Class 9 Computer Science — Building a list as you go
- 1. a) 5
- 2. c) 12
- 3. 1. 4 2. 9 3. 16 4. 25
- 4.
- 0
- none
- nought
- 5. 4
- 6. 10
- 7. 1
- 8. 6