Software Design Fall 2004 For lab: 1) read Chapter 10 of "How to think..." Dictionaries are the coolest thing in the known universe. The data structure, not the book. 2) prepare for a warmup at the beginning of lab For Monday: 1) Work on Homework 4 2) Read Chapter 11 of "How to think..." Lists ----- Ways to create a list: 1) brackets 2) range function 3) list function (works on any sequence) >>> s = 'allen' >>> list(s) 4) list comprehension Indexing, slicing and len() are the same as for strings. The in operator works with lists. So do + and * The for loop works with lists: for var in t: print var is the same as: i = 0 while i < len(t): var = t[i] print var i += 1 In this context, var is called a "loop variable" You can use any legal identifier for the loop variable. Lists are mutable ----------------- You can use the [] operator on the left side of an assignment: t = [1, 2, 3] t[1] = 17 print t Don't try this with strings! List methods ------------ Most list methods are modifiers. They change the list and return None. Try this: >>> x = range(3) >>> print x >>> x.reverse() >>> print x See more list methods at: http://www.python.org/doc/current/lib/typesseq-mutable.html Object Identity --------------- 1) Try this: >>> x = [1, 2, 3] >>> y = [1, 2, 3] >>> id(x) >>> id(y) Draw a state diagram showing x, y, and their values. Then try this: >>> x == y >>> x is y The first condition tests equality: do x and y refer to values that are equal. The second condition tests identity: do x and y refer to the same value. 2) Now change x: >>> x = y And try again: >>> x == y >>> x is y Now x and y refer to the same object. If you change the object, both names see the change: >>> x.reverse() >>> print y x and y are "aliases" 3) Assuming that t = range(3) What's the difference between: t2 = t and t2 = t[:] Draw state diagrams showing the two cases. lists as parameters ------------------- When lists are passed as arguments, they are passed by reference, which means that the parent function and the child function refer to the same object. Draw a stack diagram for this program: def delete_head(t): del t[0] x = range(3) delete_head(x) print x x and t are aliases for the same list object. changes made in delete_head are reflected in __main__ (as intended) Another way to delete the head of a list is t = t[1:] So we could put that in a function: def bad_delete_head(t): t = t[1:] x = range(3) bad_delete_head(x) print x Why doesn't that work?