# question: how do you sort on the second letter of a list of strings? >>> ls = [ "ahi", "gbc", "def" ] >>> ls Out[1]: ['ahi', 'gbc', 'def'] >>> import operator >>> sorted(ls, key=operator.itemgetter(1)) Out[1]: ['gbc', 'def', 'ahi'] # because YOU asked :) # different ways to square elements of a list >>> values = [ 1, 2, 3] >>> values Out[1]: [1, 2, 3] # traditional for loop, fine for all situations in this class >>> valuesSquared = [] >>> for x in values: … valuesSquared.append(x * x) >>> valuesSquared Out[1]: [1, 4, 9] # standard list comprehension, "squaring" is part of the definition >>> [ x * x for x in values ] Out[1]: [1, 4, 9] # define a function to compute squared value >>> def square (x): … return x * x # more general list comprehension, "squaring" can be anything function does >>> [ square(x) for x in values ] Out[1]: [1, 4, 9] # map function, apply given function to each element in sequence >>> map(square, values) Out[1]: [1, 4, 9] # map function, apply "inline, anonymous" function to each element in sequence # primarily for those that do not want to define function separately # NEVER required in this course >>> map(lambda x: x * x, values) Out[1]: [1, 4, 9] # dictionary basics # empty >>> d = { } # some initial values, using colon as separator >>> d = { 'a':13, 'b':24, 'c':39 } >>> d Out[1]: {'a': 13, 'b': 24, 'c': 39} # accessing values using keys >>> d['a'] Out[1]: 13 >>> d['b'] Out[1]: 24 >>> d['c'] Out[1]: 39 # error to use non-existent key >>> d['z'] Traceback (most recent call last): File "/Users/guestuser/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2721, in run_code exec code_obj in self.user_global_ns, self.user_ns File "", line 1, in d['z'] KeyError: 'z' # accessing all contents >>> for (k,v) in d.items(): ... print(k + '\t' + str(v)) a 13 c 39 b 24 # changing a value >>> d['c'] = 45 >>> d['c'] Out[1]: 45 >>> d['c'] += 1 >>> d['c'] Out[1]: 46 # error to update non-existent key >>> d['z'] += 1 Traceback (most recent call last): File "/Users/guestuser/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2721, in run_code exec code_obj in self.user_global_ns, self.user_ns File "", line 1, in d['z'] += 1 KeyError: 'z' # keys must be immutable >>> d = { (1,2):24, [1,2]:13 } Traceback (most recent call last): File "/Users/guestuser/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2721, in run_code exec code_obj in self.user_global_ns, self.user_ns File "", line 1, in d = { (1,2):24, [1,2]:13 } TypeError: unhashable type: 'list' # tuples, numbers, and strings are immutable >>> d = { (1,2):24, 13:[1,2], 'abc':'def' }