Nested Loops

We said earlier that the block of statements inside a loop could contain anything. This means that it can also contain another loop.

This program, for example, loops over the list inner once for each element of the list outer:

Download lists/nested_loops.cmd

>>> outer = [ 'Li' , 'Na' , 'K' ] >>> inner = [ 'F' , 'Cl' , 'Br'] >>> for metal in outer: ... for gas in inner: ... print metal + gas

LiCl

LiBr

NaCl

NaBr

If the outer loop has No iterations and the inner loop executes N times for each of them, the inner loop will execute a total of NoN times. One special case of this is when the inner and outer loops are running over the same list of length N, in which case the inner loop executes N2 times. This can be used to generate a multiplication table; after printing the header row, we use a nested loop to print each row of the table in turn, using tabs to make the columns line up:

Download lists/multiplication_table.py

def print_table():

'''Print the multiplication table for numbers 1 through 5.'''

# Print the header row. for i in numbers:

# Print the column number and the contents of the table, for i in numbers:

print i, for j in numbers:

print '\t' + str(i * j), print # End the current row.

Here is print_table's output:

Here is print_table's output:

Download lists/multiplication_out.txt

>>> from multiplication_table import * >>> print_table()

112 3 4

Notice when the two different kinds of formatting are done: the print statement at the bottom of the program prints a new line when outer loop advances, while the inner loop includes a tab in front of each item.

Geneticists describe C. elegans (nematodes, or microscopic worms) using three-letter short-form markers. Examples include Emb (embryonic lethality), Him (High incidence of males), Unc (Uncoordinated), Dpy (dumpy: short and fat), Sma (small), and Lon (long). We can thus keep a list:

Download lists/celegans.cmd

>>> celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] >>> celegans_markers

It turns out that Dpy worms and Sma worms are difficult to distinguish from each other, so they are not as useful as markers in complex strains. We can produce a new list based on celegans_markers, but without Dpy or Sma, by taking a slice of the list:

Download lists/celegansl.cmd

>>> celegans_markers = ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma'] >>> useful_markers = celegans_markers[0:4]

This creates a new list consisting of only the four distinguishable markers (see Figure 5.7, on the following page).

The first index in the slice is the starting point. The second index is one more than the index of the last item we want to include. More rigorously,

Was this article helpful?

0 0

Post a comment