Software Design Spring 2007 For today you should have: 1) read Chapter 10 2) worked on Homework 4 3) prepared for a quiz For Monday you should: 1) read Chapter 11 2) work on Homework 4 Lists ----- Ways to create a list. 1) bracket operator: [], [1], [1, 2, 3] 2) list function: list('allen') this is why I don't recommend using list as a variable name 3) other functions that return lists: range(3) 4) slice operator: t[1:3], t[:] 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 In this context, var is called a "loop variable" You can use any legal identifier for the loop variable. List vocabulary --------------- compound object: mutable: index: element: slice: Lists are mutable ----------------- You can use the [] operator on the left side of an assignment: t = range(3) t[1] = 17 print t Now it really matters when two variables refer to the same list. Run: python lumpy_test.py Modify lumpy_test.py with this code: t1 = range(3) t2 = t1 t2[1] = 17 print t1 And then this: t1 = range(3) t2 = t1[:] t2[1] = 17 print t1 the is operator --------------- Try this: t1 = range(3) t2 = t1[:] print t1 == t2 print t1 is t2 These lists are equal but not the same! print id(t1), id(t2) identity (shallow equality): same object equivalence (deep equality): same value 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 deleteHead(t): del t[0] x = range(3) deleteHead(x) print x x and t are aliases for the same list object. changes made in deleteHead are reflected in __main__ (as intended) Now draw a stack diagram for this one: def badDeleteHead(t): t = t[1:] print t x = range(3) badDeleteHead(x) print x