CS 1

Lecture 8

Professor Devin Balkcom
devin@cs.dartmouth.edu
office: Sudikoff 211

http://www.cs.dartmouth.edu/~cs1

Primitive type assignment

x = 5
y = x
y = 10

print x, y    #  5 10

Changing the value in y didn't change the value in x.

List assignment

ivies = ["Dartmouth", "Columbia", 
  "Princeton"]

expensive_schools = ivies
expensive_schools[2] = "Stanford"

print ivies

Changing the list referred to by expensive_schools changed the list referred to by ivies! Why?

List vars don't store lists

Lists store references to lists.

List aliasing

schools = mice

Aliasing: two variables refer to the same object.

Aliasing can be bad

ivies = ["Dartmouth", "Columbia", 
  "Princeton"]

expensive_schools = ivies
expensive_schools[2] = "Stanford"

print ivies

The list referred to by 'ivies' suddenly changed, with no obvious change made to ivies. Weird and bad.

Aliasing and functions

Why does Python allow aliasing? Copying a list, slow; copying an address, faster.

  • function call: values of actual parameters are copied into formal parameters.
  • List variables store addresses (references).
  • Therefore, the function might have a formal parameter that stores a reference to a list object.

Reversing a list

Previously, reverse_list.py

We can wrap in a function, making use of aliasing: reverse_list_func.py

Copying a list

The list()function copies a list, and returns the address of the new list.

test_list = [1, 3, 5, 7, 9, 11]
rlist = list(test_list)
reverse_list(rlist)
print "Reversed:  " + str(rlist)
print "Not:  " + str(test_list)

Appending to a list

dwarfs = ["Happy", "Dopey", "Doc", 
  "Sleepy", "Bashful", "Sneezy"]
dwarfs.append("Grumpy")
print dwarfs

Output:

["Happy", "Dopey", "Doc", 
  "Sleepy", "Bashful", 
  "Sneezy", "Grumpy"]

What's with the weird dot notation?

Deleting from a list

primes = [2, 3, 5, 7, 9, 11]
del primes[4]

Notice that every item to the right of the deleted item moves one spot to the left (has its index dereased).

Files