Workbook for Chapter 3 of Explorations in Computing

Section 3.4: List Indexes

T27. Make a small list of strings to use for testing index expressions:

In [1]:
notes = ['do', 're', 'mi', 'fa', 'sol', 'la', 'ti']

T28. Use an index expression to get the first item in the list:

In [2]:
notes[0]
Out[2]:
'do'

T29. Because there are seven strings in this list we can find the last one at location 6:

In [3]:
notes[6]
Out[3]:
'ti'

T30. Type another expression to access the last item:

In [4]:
notes[len(notes) - 1]
Out[4]:
'ti'

T31. Try asking Python for values at other locations, using any index between 0 and 6. Is the result what you expected?

In [5]:
notes[2]
Out[5]:
'mi'
In [6]:
notes[4]
Out[6]:
'sol'

T32. Ask for an index that is past the end of the list:

In [7]:
notes[12]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-755a6dd7e200> in <module>()
----> 1 notes[12]

IndexError: list index out of range

T33. Next try some expressions using in, which should evaluate to True or False, depending on whether the list contains the specified item:

In [8]:
're' in notes
Out[8]:
True
In [9]:
'bzzt' in notes
Out[9]:
False

T34. Use Python's index method to find out where the items are located:

In [10]:
notes.index('re')
Out[10]:
1
In [11]:
notes.index('bzzt')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-5e88cc83c749> in <module>()
----> 1 notes.index('bzzt')

ValueError: 'bzzt' is not in list

T35. Enter a for loop in the code cell below. The loop should use range to iterate over the notes list and print something about each note:

In [12]:
for i in range(0, len(notes)):
    print(notes[i], 'has', len(notes[i]), 'letters')
do has 2 letters
re has 2 letters
mi has 2 letters
fa has 2 letters
sol has 3 letters
la has 2 letters
ti has 2 letters

T36. Enter the for loop that prints the square roots of numbers from 1 to 10 (don't forget to import the sqrt function if you haven't done it already):

In [13]:
from math import sqrt
for i in range(1, 11):
    print(i, sqrt(i))
1 1.0
2 1.4142135623730951
3 1.7320508075688772
4 2.0
5 2.23606797749979
6 2.449489742783178
7 2.6457513110645907
8 2.8284271247461903
9 3.0
10 3.1622776601683795

T37. Repeat the previous exercise, but this time use range(1,11,2). Did Python execute the body of the loop only for odd values of i? Do you see why?

In [14]:
for i in range(1, 11, 2):
    print(i, sqrt(i))
1 1.0
3 1.7320508075688772
5 2.23606797749979
7 2.6457513110645907
9 3.0

partial_total

T38. Enter the definition of the partial_total function from Figure 3.6 in the code cell below. You can either type the definitions shown in the figure, or copy and paste the code from partialtotal.py.

After the definition is complete type ⌃⏎ to execute the cell to make the function available in this notebook.

In [15]:
def partial_total(n,a):
    """"
    Compute the total of the first
    n items in list a.
    """
    sum = 0
    for i in range(0,n):
        sum += a[i]
    return sum

Make a list named a containing the numbers 3, 5, 2, 16, and 7:

In [16]:
a = [3, 5, 2, 16, 7]

How would you call partial_total to get the sum of the first three numbers? Type the expression in the code cell below to verify your answer.

In [17]:
partial_total(3, a)
Out[17]:
10

If you're not sure how partial_total works add this print statement to the for loop, right after the statement that adds a[i] to sum. Type ⌃⏎ to update the function definition, then call the function with different values of n.

        print('i =', i, 'sum =', sum)

T39. What happens if you pass a number to partial_total that is larger than the number of items in the list? For example, what does Python do if a has five items and you call partial_total(7,a)?

In [18]:
partial_total(7, a)
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-18-b677ba3d3acb> in <module>()
----> 1 partial_total(7, a)

<ipython-input-15-083cbd96b0ef> in partial_total(n, a)
      6     sum = 0
      7     for i in range(0,n):
----> 8         sum += a[i]
      9     return sum

IndexError: list index out of range

♦ Add statements to your definition of partial_total so the function returns a correct value even if n is too large. If n is greater than the number of items in the list, simply return the sum of all the items.

♦ Repeat the call to partial_total(7,a). Does your function return the correct result now?