Programs that Hold Many Values
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.
A list does not have to be written out in full before a program can use it. You can start with an empty one — square brackets with nothing between them — and add to it as the program runs. The way to add is append: write the list's name, then a dot, then append, and in the brackets the value to add. It goes on the end, so a list built this way comes out in the order the values were added.
The list grows by one every time append runs
That sentence is the whole skill, and the trap is in the last three words. Inside a plain loop, append runs once per trip and the list ends up as long as the loop is. Inside an if, it runs only on the trips that get through the test, so the list is shorter than the loop — sometimes much shorter, and sometimes empty. Inside a loop within a loop it runs once for every time the deepest line runs. So the length of the finished list is never read off the range. It is counted from how often that one line was actually reached.
Worked example
There is no loop at all in this one. What does it print?
tally = [] tally.append(4) tally.append(9) print(len(tally))
The list starts empty, so at that moment it holds nothing and its length is 0.
An empty list is a real list. It has a name and a length, and the length happens to be nought.
Try it together
Now put an append inside a loop, and watch the length as it goes.
thirds = []
for n in range(1, 4):
thirds.append(n * 30)
print(len(thirds))The printing is inside the loop, so there is a number for every trip.
1.What is printed on the first trip round?
Have a go
Have a go on your own. What does this program print?
fives = []
for n in range(0, 6):
fives.append(n * 5)
print(fives[4])Ready to practice?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.