ERROR ON PREV
How to Program, Part III
  1. How to Program, Part I
  2. How to Program, Part II
  3. How to Program, Part III
  4. How to Program, Part IV
  5. How to Program, Part V
  6. How to Program, Part VI
  7. exercises
  8. pyMPI tutorial
  9. Calculating PI, Part I
  10. Calculating PI, Part II
  11. Calculating PI, Part III
  12. Dividing Work
  13. More MPI
  14. Poogle - Web Search
  15. Mandelbrot Sets
  16. Mandelbrot, The Code
  17. Mandelbrot, The Images
  18. Mandelbrot In CUDA
  19. Conway's Life, Part I
  20. Life Code Listing
  21. Conway's Life, Part II
  22. MPI Life Code Listing

How to Program, Part III

This lesson is about lists. You can think of lists as being like shelves. The program

list1.py
1a = ["strawberry","apple"]
2print a
$ python ./list1.py
['strawberry', 'apple']

creates a list with three elements, each of which is a string. Think of the comma separated list of items inside the square brackets as a kind of storage case. Each item on the list is in its own shelf, which has a number. The apple is on shelf 0, and the strawberry is on shelf 1.

We can use this number to find out what's on a shelf, or to replace the contents of a shelf.

list2.py
1a = ["strawberry","apple"]
2print a
3a[1] = "pear" # replaces the contents of shelf one
4print a
5print a[0] # prints the contents of shelf zero
$ python ./list2.py
['strawberry', 'apple']
['strawberry', 'pear']
strawberry

The third line of the program replaces the contents of shelf 1 with "pear." The last line of the program prints out the contents of shelf 0.

If we want, we can make our shelf unit larger.

list3.py
1a = ["strawberry","apple"]
2a.append("orange") # Adds a new shelf. 
3print a
$ python ./list3.py
['strawberry', 'apple', 'orange']

The "append" method increased the size of the shelf, and puts "orange" into the new shelf.

We can shorten this example by using the "+" sign to join two lists together:

list3v2.py
1a = ["strawberry","apple"]
2a = a + ["orange"] # Adds a new shelf. 
3print a
$ python ./list3v2.py
['strawberry', 'apple', 'orange']

Or if we like, we can use the super short-hand of saying "a +=". It means the same thing as "a = a +".

list3v3.py
1a = ["strawberry","apple"]
2a += ["orange"] # Adds a new shelf. 
3print a
$ python ./list3v3.py
['strawberry', 'apple', 'orange']

You can print the elements of your shelf in order by doing this:

list4.py
1a = ["meat","fruit","veggies"]
2for v in a:
3    print v
$ python ./list4.py
meat
fruit
veggies

Try it!

Now we can change things up and print each item in the list with a number next to it:

list5.py
1a = ["meat","fruit","veggies"]
2for i in range(len(a)):
3    print i,"]",a[i]
$ python ./list5.py
0 ] meat
1 ] fruit
2 ] veggies

The function "len" tells you the length of a list. Thus "len(a)" is 3.

If you haven't guessed, the function "range" creates a list of integers.

prange.py
1print range(10)
$ python ./prange.py
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Perhaps less obviously, strings are lists of characters:

strischars.py
1for c in "wow":
2    print c
$ python ./strischars.py
w
o
w

One of the cool things about lists is that you can nest one inside the other

list6.py
1tictactoe = [
2  [ 'X', '-', 'O' ],
3  [ 'O','X','-'  ],
4  [ '-'  ,'O','X']]
5 
6now count the number of X's and O's
7on the board and display the result
8xs = 0
9os = 0
10for row in tictactoe:
11    for col in row:
12        if col == 'X':
13            xs = xs + 1
14        elif col == 'O':
15            os = os + 1
16print "xs=",xs,os=",os
$ python ./list6.py
xs= 3  os= 3

The above example of a list of lists shows you how you might represent the game board for tic tac toe. Try changing the placement of X's and O's on the board, and check that the counts come out right. There are many uses for lists, and you can nest them as deeply as you want. You can have a list of lists of lists of lists of lists.

Note that because strings are just lists of characters, this works the same way:

list6v2.py
1tictactoe = [
2  "X-O",
3  "OX-",
4  "-OX"]
5 
6now count the number of X's and O's
7on the board and display the result
8xs = 0
9os = 0
10for row in tictactoe:
11    for col in row:
12        if col == 'X':
13            xs = xs + 1
14        elif col == 'O':
15            os = os + 1
16print "xs=",xs,os=",os
$ python ./list6v2.py
xs= 3  os= 3

Problems:

  1. Why does this program produce an index error?
    wrong31.py
    1r = ['apple','pear','banana']
    2for i in range(4):
    3  print i,'] ',r[i]
    $ python ./wrong31.py
    0 ]  apple
    1 ]  pear
    2 ]  banana
    3 ] 
    Traceback (most recent call last):
      File "./wrong31.py", line 3, in <module>
        print i,'] ',r[i]
    IndexError: list index out of range
    
  2. Why does this program produce an index error?
    wrong32.py
    1r = ['apple','pear','banana']
    2for i in [1,2,3]:
    3  print i,'] ',r[i]
    $ python ./wrong32.py
    1 ]  pear
    2 ]  banana
    3 ] 
    Traceback (most recent call last):
      File "./wrong32.py", line 3, in <module>
        print i,'] ',r[i]
    IndexError: list index out of range
    
  3. This program is supposed to print ['h', 'e', 'l', 'l', 'o']. What's wrong with it?
    wrong33.py
    1li = []
    2for c in "hello":
    3  [].append(c)
    4print li
    $ python ./wrong33.py
    []
    
  4. What does this program do?
    what31.py
    1a = [1,9,2,3,0,5,10,7]
    2mn = a[0]
    3for val in a:
    4  if val < mn:
    5    mn = val
    6print mn
  5. What does this program do?
    what32.py
    1a = [1,9,2,3,0,5,10,7]
    2mx = a[0]
    3for i in range(1,len(a)):
    4  if a[i] > mx:
    5    mx = a[i]
    6print mx
  6. What does this program do?
    what33.py
    1a = [1,9,2,3,0,5,10,7]
    2sm = a[0]
    3for i in range(1,len(a)):
    4    sm += a[i]
    5print sm
  7. What does this program do?
    what34.py
    1a = [1,3,9]
    2fa = a[0]
    3for i in range(1,len(a)):
    4    fa = fa * a[i]
    5print fa
  8. Write a program that creates a list of the even numbers between 1 and 20. Use the append() function and a loop.
  9. Write a program that creates a list of the even numbers between 1 and 20 followed by the odd numbers in that same range. Use the append() function and two loops.