COMP 200: Elements of Computer Science
Spring 2013

Iterating (a.k.a. Looping)

So we can now make lists and fill them with all sorts of values. Now what? We need to process all those values in order to extract something useful out of them. How can we step through a list one element at a time? Here we introduce one technique: the for loop.

A for loop fundamentally steps through all the elements of an iterable entity, which is anything that has elements that can be stepped through one at a time. This includes lists and strings, as we'll see here. The beauty of a for loop, however, lies in the fact that it will also perform a given sequence of operations for every element that it iterates through.

Let's try a very simple example:

In turn, each element of the list numbers is placed in the variable number. The indented code, the loop body, is performed for each value that number takes on. So, in this case, number becomes 1, and that is printed, then number becomes 6, and that is printed, etc. I.e., this prints each element of the list, from first to last.

We can take this idea to define a function to print the elements of whatever iterable is given to the function.

As you can see, this works regardless of the kinds of data in the input list. It also works on strings, rather than lists. The same function would work on other kinds of iterables that we haven't seen yet.

To do something a bit more useful, let's sum the squares of a list of numbers, a common computation in statistics.

This code initializes the variable total to be zero. Then, for each list element in turn, we'll call the element number and add its square to total. Finally, we return the computed total. Thus, this function works by repeatedly changing total to be more and more of the eventual result. We often call this “accumulating” the result, and total is an accumulator variable.

This also illustrates another way of introducing local variables. The variable number is local to the loop — the name doesn't mean anything outside the loop. Similarly, the variables numbers and total are local to the function. Again, this allows us to choose variable names without worrying about what names are used in other code.

Similarly, we could instead build a new list of the squares of the original list values.

Again, we are accumulating the desired value, which this time is a list.

What happens in the two previous examples if we omit the initialization? In sum_squares(), comment out the line total = 0, and then use the function. In square_list(), do the same with squares = [].

Exercises

Follow these ideas to define functions that accomplish the following:

We will be practicing with loops all week.