Lists

Atomic data, such as an integer or floating point number, is called a scalar. Think of a scalar as data needing a single memory cell of storage. Programming languages also provide methods for processing lists of data, which are stored in multiple memory cells. These notes explain how to program lists with Python. By the end, you'll be able to write code that, for instance, sums a list of numbers. If you want to see these concepts in action, check out these screencasts: lists1  lists2

Putting elements in lists

In Python, you initialize a list variable by assigning the empty list to it, e.g.,
 
    colors=[] 

You can also create a list and initialize it with data using a single statement:
 
  colors=['red','blue','green']

One you've created a list you can get to its elements with an index, e.g.,

    print colors[0]   # prints red
    print colors[1]   # prints blue
    print colors[2]  # prints green

You can also modify elements using an index:
 
    colors[2]='purple'

You  cannot access or modify an element of a list unless the list already has that element. So the following code will give errors:
 
    list=[]
    list[0]=4 # error -- element 0 doesn't exist yet, so can't modify it
    print list[2]  # error -- element 2 doesn't exist yet, so can't read
 
    list2=[1,2]
    list2[3]=7 # error, only two elements in the list.

 
Python also provides functions to append to a list:
 
    colors = ['red', 'blue','green']
    colors.append('purple')    # gives ['red','blue','green','purple']

and insert an element somewhere in the list:
 
    colors.insert(2,'yellow')  #gives  ['red,'blue','yellow','green',purple']

Note that append and insert calls are object-oriented function calls-- you provide the list name (colors) followed by a '.' and then the function name (append or insert).

Iterating through a list

Often, you'll want to visit each element of a list. Here's a sample:
 
   students = ['bob', 'joe', 'sylvia']
    i=0
    while i<3:
        print students[i]
        i=i+1
 
What happens if we go to far and try to print a 4th element? Consider the following code:
 
   
students= ['bob', 'joe', 'sylvia']
    i=0
    while i<4:
        print students[i]
        i=i+1
 
Unfortunately, you'll see this  'index out of range' error a million times in your programming life.

What we really want is to find out the size of the list, and use that number for the limit on the while loop.
 
Python provides some help with the len function. It accepts one parameter which is the list:
 
    len(students)

and it returns the number of elements in the list.

You could call len and put the return value in a variable, e.g.,

    numStudents = len(students)

But usually we use len within a while loop. Used as part of a while, len allows us to write code that will work on any list, no matter what its size. Here's how we'd use it for our student example:

students = ['bob', 'joe', 'sylvia']
i=0
while i<len(students):
print students[i]
i=i+1

Instructor Demo: Comparing the scores of two golfers

Copying and Aliasing

The following statement does NOT make a copy of a list:
 
    list1=list2
 
It creates an alias-- both variables will point at the same memory cells.





To illustrate aliases, consider the following code:
 
    list1=[1,2,3]
    list2=list1           
    list2[1]=55
    print list1
    print list2
 
What will be printed?
 
You can create a copy of a list using a statement like the following:
 
    list2=list1[:]
 
This code:

    list1=[1,2,3]
    list2=list1[:]           
    list2[1]=55

will leave list1 as [1,2,3], changing only list2 to [1,55,3]

The ':' syntax is an example of the get range operation of a list.
 
    list2=list1[0:2] # returns the first three elements of list1. 


In-Class Problems

1. Which of the following will cause errors? Enter them in the interpreter to check. Put your answers on your portfolio page for this lab.
 
a.  list1[0]='abc'
 
b.   list2=[1,2,3]
      list2[3]=4
 
c.  list2=[1,2,3]
     list2.insert(3,4)  
 
d.  list2=[1,2,3]
     list2.append(4)
 
2. This problem is the first step in creating a Mastermind game. Write a program that allows the user to enter four colors. The user can enter each color on a separate line, and the program should prompt them for each color, as shown below:

Please enter a color: red
Please enter a color: blue
Please enter a color: green
Please enter a color: purple

Write the code so that it initializes an empty list above a loop, then loops four times, reading in and appending a color to the list on each iteration. After the loop, print out the list to see if you've built it successfully. For now, don't worry about checking if the input color is a valid color. Call this program getColorsAppend.py
 
3. Copy your program in (2) to a file getColorsModify.py. This program will do the same thing, but using lists in a different way. This time, Initialize the list as a list of four 0s. As you iterate, modify each list element with the color input by the user. Call this program getColorsModify.py.


4.
Programmer Milestone 2: A major milestone for a beginning programmer is the 'total of a list' problem: compute the sum of a list of integers, no matter how big the list. Write code that sums the elements of a list of any size, e.g. for list=[3,5,9] the program would calculate 17.

When you complete these programs, document them in your portfolio page for this lab.


Recent site activity