% class-6 talking points This week: comprehensions and dictionaries - the heart of Pythonic style! Quiz: (Try not to spend too much time on this) almost everyone finished this fast - but almost everyone made several important errors! these aren't trick questions or obscure corners - they are fundamental misunderstanding these points results in common errors (usually harder to find) 4. y[1] is the second element, not the first 3. y[1] = 99 also updates x, x and y are aliases (sharing, need for copy module) 2. s.append(['e','f']) -> ['a','b','c','d',['e','f']] append adds *one element*, here that element is itself a list, nested likewise s.append('d') -> ['a','b','c','d'] not [..[d]],element is just 'd' append vs. extend, extend vs. + 1. s.append(d) == None, append is a mutator, changes s but returns None! There is a HUGE disinction regarding operators, methods, functions *pure functions*, *functional* operators - do not change args, return new value *mutators* - change arg, do *not* return value (return None in Python) Huge impact on programming style, alternate *functional programming* universe: sort vs. sorted (demo right in interpreter) also x if c else y vs if...: + vs. append etc. List comprehensions: comprehensions.py Generate a new list from an existing collection Review little tuple database from last week Show for loop to build up list, compare to list comprehension Show more elaborate pattern/expr (aside: string formating is not just for print) map and filter patterns comprehensions vs. built-in functions comprehensions are more versatile, Pythonic functions support functional programming style, like Lisp, Haskell, F#, ... Dictionaries: Key/value pairs with *unique* keys. for databases, lookup tables. Much computing is looking things up. Keys must be hashable (immutable) - numbers, strings, tuples but not lists Chapter 13 word frequency example is very nice Show Roman numerals: roman.py, nice combo of dict, comprehension, list Mention Norvig spelling corrector.py - uses everything so far, including regexp Quiz, break, presentations sets - collections without order and repetition, demo set.py arrays - all the elements are the same type, efficient numerical (and other) cals arrays are not built in! Must get numpy. SeaPIG this Thurs, Nov 18, 7pm, Capitol Hill Reductions, product.py: builtin: sum, max, min, all, any reduce function: motivate operator module and lambda expressions lambda is used heavily with map and filter - but not needed with comprehensions That's it folks, full Pythonic style. Next two weeks - object-oriented prog.