Lecture 8
Professor Devin Balkcom
devin@cs.dartmouth.edu
office: Sudikoff 211
x = 5
y = x
y = 10
print x, y # 5 10
Changing the value in y didn't change the value in x.
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?
Lists store references to lists.
schools = mice
Aliasing: two variables refer to the same object.
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.
Why does Python allow aliasing? Copying a list, slow; copying an address, faster.
Previously, reverse_list.py
We can wrap in a function, making use of aliasing: reverse_list_func.py
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)
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?
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).