Programs that Hold Many Values

Looping over a list

Follow a loop that takes each value of a list in turn, and work out the total, the count or the largest value it leaves behind.

A counting loop hands you numbers you asked for: range decides them and the list, if there is one, has nothing to do with it. There is a second kind of for loop, and it hands you the values that are actually in a list, one at a time, in the order they sit there. You write it as for, then a name of your choosing, then in, then the list. The name holds a value out of the list on each trip — not a position, and not a count.

The list decides how many trips there are

You never write down how many times this kind of loop goes round. The list already knows, and the loop goes round once for each value in it and then stops. Two things follow that are worth having ready. A list with nothing in it means the body never runs at all, and nothing that was set up before the loop is changed by it. And whatever the loop leaves behind — a total, a count, the largest so far — has to be set up before the loop starts, because a variable made inside the body would be made afresh on every trip.

Worked example

What does this program print?

widths = [10, 4, 6]
for w in widths:
    print(w)
print(len(widths))
  1. First trip: w holds 10, the first value in the list, and 10 is printed.

    The loop reached into the list and took a value out. Nothing said position 0, and nothing had to.

Try it together

Now one where the variable set up before the loop goes down rather than up, and is printed every time round.

changes = [8, 5, 2, 1]
level = 20
for c in changes:
    level = level - c
    print(level)

Follow level rather than c, and write down what it holds after each trip.

    1.What is the first number printed?

    Have a go

    Have a go on your own. What does this program print?

    counts = [2, 6, 3]
    total = 0
    for c in counts:
        total = total + c
    print(total)

    Ready to practice?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet