http://www.cs.cornell.edu/courses/cs/8sp Lecture : Lists and Sequences (Sections.-.,.4-.6,.8-.) CS Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]
Lecture Announcements Last call for a one-on-one! CMS: OPTIONAL: one-on-ones Prelim is March. LAST DAY to register a conflict or a need for accommodation. See website: http://www.cs.cornell.edu/courses/cs/8sp/exams/index.php CMS: Prelim conflicts A Revisions: open from Mar st thru Mar 7, :9pm. just means not done. many people got a due to test cases.
Lecture Announcements A is out and about! Handout provides links to worked examples of diagramming call frames, objects, variables, etc. Preparatory to starting A: (a) immediately try those worked examples (b) go to office/consulting hours if you have any difficulty This will make A go much smoother!
Sequences: Lists of Values s = 'abc d' String 4 List x = [, 6,, 9,, ] 4 a b c d 6 9 Put characters in quotes Use \' for quote character Access characters with [] s[] is 'a' s[] causes an error s[:] is 'ab' (excludes c) s[:] is 'c d' Put values inside [ ] Separate by commas Access values with [] x[] is x[6] causes an error x[:] is [, 6] (excludes nd ) x[:] is [9,, ] Sequence is a name we give to both 4
Lists Have Methods Similar to String x = [, 6,, 9,, ] <list>.index(<value>) Return position of the value ERROR if value is not there x.index(9) evaluates to <list>.count(<value>) Returns number of times value appears in list x.count() evaluates to But to get the length of a list you use a function, not a class method: len(x) x.len()
A Word about Testing Suppose you hear a rumor that the count method is not implemented correctly. >>> lab_scores = [, 6,, 9,,, 8,,7] >>> lab_scores.count() Looks good to me! Are we done? 6
What should I be testing? Common Cases: typical usage (see previous slide) Edge Cases: live at the boundaries Target location in list: first, middle, last elements Input size:,,, many (length of lists, strings, etc.) Input Orders: max(big, small), max(small, big) Element values: negative/positive, zero, odd/even Element types: int, float, str, etc. Expected results: negative,,,, many Not all categories/cases apply to all functions. Use your judgement! 7
Things that Work for All Sequences s = slithy x = [, 6, 9, 6,, ] s.index( s ) s.count( t ) len(s) 6 s[4] h s[:] li s[:] thy s[ ] h s + toves slithy toves s * slithyslithy t in s True methods built-in fns slicing operators x.index() x.count(6) len(x) 6 x[4] x[:] [6, 9] x[:] [6,, ] x[ ] x + [, ] [, 6, 9, 6,,,, ] x * [, 6, 9, 6,,,, 6, 9, 6,, ] in x True 8
Wrong: x, 6, 7, - Representing Lists Correct: x id id 7 4 - list x = [, 7, 4,-] Indices 9
Lists vs. Class Objects List Attributes are indexed Example: x[] Objects Attributes are named Example: p.x x id id list p id id Point 7 4 - x y z
Lists Can Hold Any Type list_of_integers = [,7,4,-] list_of_strings = [ h, i,, there! ] list_of_integers id id 7 4 - list list_of_strings id id list h i there!
No Really, Lists Can Hold Any Type! list_of_points = [Point(8,,), Point(6,,) ] list_of_points id id id id id6 id7 list id Point x 8 y z id Point x 6 y z id6 Point x 4 y 4 z id7 Point list_of_various_types id9 id9 x y z list.46 happy id id Point x y z
Lists of Objects List elements are variables Can store base types and ids Cannot store folders p id id Point p = Point(,, ) p = Point(4,, 6) p = Point(7, 8, 9) x = [p,p,p] p p x id id id4 How do I get this y? x[].y x y z id Point x 4 y z 6 id Point x 7 y 8 z 9 id4 id id id list
List Assignment Format: <var>[<index>] = <value> Reassign at index Affects folder contents Variable is unchanged Strings cannot do this Strings are immutable x = [, 7,4,-] x[] = 8 s = Hello! s[] = J TypeError: 'str' object does not support item assignment x s id Hello! id 7 4 - x 8 list
List Methods Can Alter the List x = [, 6,, 9] See Python API for more <list>.append(<value>) Adds a new value to the end of list x.append(-) changes the list to [, 6,, 9, -] <list>.insert(<index>,<value>) Puts value into list at index; shifts rest of list right x.insert(,-) changes the list to [, 6, -,, 9] <list>.sort() What do you think this does?
Execute the following: >>> x = [, 6,, 9, ] >>> x[] = - >>> x.insert(, ) What is x[4]? A: B: 9 C: - D: ERROR E: I don t know st Clicker Question 6
st Clicker Answer Execute the following: >>> x = [, 6,, 9, ] >>> x[] = - >>> x.insert(, ) What is x[4]? A: B: 9 C: - D: ERROR E: I don t know CORRECT x id id 6 x9-4 list (Original elements -4 are shifted down to be elements -) 7
Recall: identifier assignment à no swap import shapes def swap(p, q): tmp = p p = q q = tmp p = shapes.point(,,) q = shapes.point(,4,) swap(p, q) p id6 q id7 Call Frame swap p id7 q id6 tmp id6 RETURN NONE id6 Point x y z id7 Point x y 4 z At the end of swap: parameters p and q are swapped global p and q are unchanged 8
Recall: Attribute Assignment à swap! import shapes def swap(p, q): tmp = p.x p.x = q.x q.x = tmp p = shapes.point(,,) q = shapes.point(,4,) swap(p, q) p id6 q id7 Call Frame swap p id6 q id7 tmp RETURN NONE id6 Point x y z id7 Point x y 4 z At the end of swap: parameters p and q are unchanged global p and q are unchanged, attributes x are swapped 9
nd Clicker Question def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] x id4 b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] What gets printed? A: B: 6 C: Something else D: I don t know id4 4 7 6 4
def swap(b, h, k): nd Clicker Answer """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] x id4 b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] What gets printed? A: CORRECT B: 6 C: Something else D: I don t know Swaps b[h] and b[k], because parameter b contains name of list. id4 4 7 6 4
nd Clicker Explanation () def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h k 4 id4 4 7 6 4
nd Clicker Explanation () def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h id4 4 7 6 4 temp 6 k 4
nd Clicker Explanation () def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h temp 6 k 4 id4 4 7 6 4 4
nd Clicker Explanation (4) def swap(b, h, k): """Procedure swaps b[h] and b[k] in b Precondition: b is a mutable list, h and k are valid positions in the list"" temp= b[h] b[h]= b[k] b[k]= temp x = [,4,7,6,] swap(x,, 4) print x[] x swap id4 Call Frame b id4 h temp 6 k 4 id4 4 7 6 4 6 RETURN None
List Slices Make Copies x = [, 6,, 9] y = x[:] x id y id6 id 6 9 list copy means new folder id6 6 list 6
Execute the following: >>> x = [, 6,, 9, ] >>> y = x[:] >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know rd Clicker Question 7
rd Clicker Answer Execute the following: >>> x = [, 6,, 9, ] >>> y = x[:] >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know CORRECT x id y id6 id 6 9 4 id6 6 9 list 7 list 8
Execute the following: >>> x = [, 6,, 9, ] >>> y = x >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know 4 th Clicker Question 9
4 th Clicker Answer Execute the following: >>> x = [, 6,, 9, ] >>> y = x >>> y[] = 7 What is x[]? A: 7 B: C: 6 D: ERROR E: I don t know CORRECT x id y id id 6 9 4 7 list
Lists and Expressions / th Clicker Q List brackets [] can contain expressions This is a list expression Python must evaluate it Evaluates each expression Puts the value in the list Example: >>> a = [+,+4,+6] >>> a [, 7, ] Execute the following: >>> a = >>> b = 7 >>> x = [a, b, a+b] What is x[]? A: 'a+b' B: C: 7 D: ERROR E: I don t know
Lists and Expressions / th Clicker A a b 7 x id id 7 list Execute the following: >>> a = >>> b = 7 >>> x = [a, b, a+b] What is x[]? A: 'a+b' B: C: 7 D: ERROR E: I don t know CORRECT
Lists and Strings Go Hand in Hand text.split(<sep>): return a list of words in text (separated by <sep>, or whitespace by default) <sep>.join(words): concatenate the items in the list of strings words, separated by <sep>. >>> text = 'A sentence is just\n a list of words' >>> words = text.split() >>> words ['A', 'sentence', 'is', 'just', 'a', 'list', 'of', 'words'] >>> lines = text.split('\n') >>> lines ['A sentence is just', ' a list of words'] >>> hyphenated = '-'.join(words) >>> hyphenated 'A-sentence-is-just-a-list-of-words' >>> hyphenated = '- '.join(lines[].split()+lines[].split()) >>> hyphenated 'A-sentence-is-just-a-list-of-words' Turns string into a list of words Turns string into a list of lines Combines elements with hyphens Merges lists, combines elements with hyphens