Sometimes the loop index should not go over the entire range of
indices, and we need to think about where to stop it early, as the
next example shows.

Example: Returning to our example from Lecture 1, we will briefly
re-examine our solution to the following problem: Given a string,
how can we write a function that decides if it has three
consecutive double letters?

In programming you often must deal with data much more complicated
than a single list. For example, we might have a list of lists, where
each list might be temperature (or pH) measurements at one location of
a study site:

Here is code to find the site with the maximum average
temperature; note that no indices are used.

averages=[]forsiteintemps_at_sites:avg=sum(site)/len(site)averages.append(avg)max_avg=max(averages)max_index=averages.index(max_avg)print("Maximum average of {:.2f} occurs at site {}".format(max_avg,max_index))

Notes:

for loop variable site is an alias for each sucessive
list in temps_at_sites

A separate list is created to store the computed averages

We will see in class how this would be written without the
separate averages list.

Nested for loops may be needed to iterate over two dimensions of
data.

Lists of lists may be used to specify more complex data. We process
these using a combination of for loops, which may need to be
nested, and Python’s built-in functions. Use of Python’s built-in
functions, as illustrated in the example here in these notes, is
often preferred.

Loops (either for or while) may be controlled using continue to
skip the rest of a loop iteration and using break to terminate
the loop altogether. These should be used sparingly!