3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] Python Type "help", "copyright", "credits" or "license" for more information. # Topic: list comprehensions. # They take this general form: # [ for in ] # Set up for some examples. L = [5, 13, -2, 77, 9] # Examples: [item + 100 for item in L] [105, 113, 98, 177, 109] [item**2 for item in L] [25, 169, 4, 5929, 81] # Imagine doing this without a list comprehension. answer = [] for item in L: answer.append(item**2) answer [25, 169, 4, 5929, 81] # Much nicer to do it in one quite easy-to-understand line. [item**2 for item in L] [25, 169, 4, 5929, 81] # Here we'll work with a list of lists. matrix = [[1, 2, 3,], [4, 5, 6], [7, 8, 9]] [row[0] for row in matrix] [1, 4, 7] # Generalize it to any column. col = 2 [row[col] for row in matrix] [3, 6, 9] matrix [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Remember the sum function? sum([4, 7, 99, 199]) 309 # We can use it in our list comprehension to sum up the rows of our matrix. [sum(row) for row in matrix] [6, 15, 24] # We can sum that to get the grand total of the values in the matrix -- cool! sum([sum(row) for row in matrix]) 45 # What if it was a less tidy list, with different levels # of nesting? L = [8, [4, 5, 6], [1, 2, 3, [8, 8], 4], [[[[5]]]]] # We'll figure that one out next week. # ---- And a couple of examples I didn't get to show you in lecture: # We can iterate over anything. But a list comprehension will # always compose a list. # Example iterating over a str: s = 'cool' [char + '!' for char in s] ['c!', 'o!', 'o!', 'l!'] # Example iterating over a dict: d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'} [k/2.0 for k in d.keys()] [0.5, 1.0, 1.5, 2.0]