Module 18 Nested Lists
Motivating this Course Module • In previous video series, introduced lists § All our examples had primitives in the lists § So we only showed one folder in visualization § Demo: x = [5,6,5,9] • But lists can contain anything! § What if they can contain objects? § Yes, primitives = objects, but ignore folders § We mean if we cannot ignore the folders
Lists of Objects • List positions are variables id13 r id10 § Can store base types list b id11 § But cannot store folders 0 id10 § Can store folder identifiers g id12 1 id11 • Folders linking to folders 2 x id13 id12 § Top folder for the list id12 § Other folders for contents id10 id11 RGB RGB • Example: RGB red 0 red 255 >>> r = introcs.RGB(255,0,0) red 0 green 255 green 0 >>> b = introcs.RGB(0,0,255) green 0 >>> g = introcs.RGB(0,255,0) blue 0 blue 0 blue 255 >>> x = [r,b,g]
Nested Lists • We have seen that lists can hold any objects § Lists are objects § Therefore lists can hold other lists! • Known as nested or multidimensional list x[2] a = [2, 1] x[1] x[2][2] b = [3, 1] x = [1, [2, 1], [1, 4, [3, 1]], 5] c = [1, 4, b] x = [1, a, c, 5] x[0] x[1][1] x[2][0] x[2][2][1]
How Multidimensional Lists are Stored • b = [[9, 6, 4], [5, 7, 7]] id2 id3 9 6 4 id1 5 7 7 9 5 id2 6 7 id3 id1 b 4 7 • b holds name of a one-dimensional list § Has len(b) elements § Its elements are (the names of) 1D lists • b[i] holds the name of a one-dimensional list (of ints) § Has len(b[i]) elements
Ragged Lists vs Tables • Ragged is 2d uneven list: b = [[17,13,19],[28,95]] id2 id1 id3 id1 0 17 b 0 0 id2 28 1 13 id3 95 1 1 2 19 • Table is 2d uniform list: b = [[9,6,4],[5,7,7]] id2 id3 9 6 4 id1 5 7 7 9 5 id2 6 7 id3 id1 b 4 7
Ragged Lists vs Tables • Ragged is 2d uneven list: b = [[17,13,19],[28,95]] id2 id1 id3 Tables are more common. id1 0 17 b 0 0 id2 28 1 13 Focus of their own video. id3 95 1 1 2 19 • Table is 2d uniform list: b = [[9,6,4],[5,7,7]] id2 id3 9 6 4 id1 5 7 7 9 5 id2 6 7 id3 id1 b 4 7
Tables are a Common Type of Data Spreadsheet Image 0 1 2 3 4 5 6 7 8 9 101112 0 1 2 3 0 1 0 5 4 7 3 2 3 1 4 8 9 7 4 5 6 2 5 1 2 3 7 8 9 3 4 1 2 9 10 11 12 4 6 7 8 0 table.csv bee.xlsx
Representing Tables as Lists • Represent as 2d list Spreadsheet § Each table row a list 0 1 2 3 § List of all rows Each row, 0 5 4 7 3 § Row major order col has a 1 4 8 9 7 value • Column major exists 2 5 1 2 3 § Less common to see 3 4 1 2 9 § Limited to some 4 6 7 8 0 scientific applications d = [[5,4,7,3],[4,8,9,7],[5,1,2,3],[4,1,2,9],[6,7,8,0]]
Image Data: 2D Lists of Pixels 0 1 2 3 4 5 6 7 8 9 101112 id23 0 1 RGB 2 3 4 red 255 smile.py 5 6 7 green 255 8 9 10 blue 255 11 12 id1 id2 id1 b list list id2 id23 id3 id24 … …
Overview of Two-Dimensional Lists • Access value at row 3, col 2: 0 1 2 3 d[3][2] d 5 4 7 3 0 1 4 8 9 7 • Assign value at row 3, col 2: 5 1 2 3 2 d[3][2] = 8 4 1 2 9 3 6 7 8 0 4 • There is an odd symmetry § Number of rows of d: len(d) § Number of cols in row r of d: len(d[r])
Slices and Multidimensional Lists • Only “top-level” list is copied. x = b[:2] • Contents of the list are not altered • b = [[9, 6], [4, 5], [7, 7]] x id5 b id1 id2 id5 9 id2 id1 6 id3 id3 id2 id3 4 id4 5 id4 7 7
Slices and Multidimensional Lists • What are the contents of • Create a nested list the list (with name) in b ? >>> b = [[9,6],[4,5],[7,7]] • Get a slice A: [[9,6],[4,5],[7,7]] >>> x = b[:2] B: [[9,6],[4,5,10]] • Append to a row of x C: [[9,6],[4,5,10],[7,7]] D: [[9,6],[4,10],[7,7]] >>> x[1].append(10) E: I don’t know • x now has nested list [[9, 6], [4, 5, 10]]
Shallow vs. Deep Copy • Shallow copy: Copy top-level list § Happens when slice a multidimensional list • Deep copy: Copy top and all nested lists § Requires a special function: copy.deepcopy • Example: >>> import copy >>> a = [[1,2],[2,3]] >>> b = a[:] # Shallow copy >>> c = copy.deepcopy(a) # Deep copy
Relationship to Standard Lists • Functions on nested lists similar to lists § Go over (nested) list with for-loop § Use accumulator to gather the results • But two important differences § Need multiple for-loops § One for each part/dimension of loop § In some cases need multiple accumulators § Latter true when result is new table
Simple Example def all_nums(table): """Returns True if table contains only numbers Precondition: table is a (non-ragged) 2d List""" result = True Accumulator # Walk through table for row in table: First Loop # Walk through the row Second Loop for item in row: if not type(item) in [int,float]: result = False return result
Transpose: A Trickier Example def transpose(table): """Returns: copy of table with rows and columns swapped 1 2 Precondition: table is a (non-ragged) 2d List""" 3 4 5 6 result = [] # Result (new table) accumulator # Loop over columns # Add each column as a row to result 1 3 5 2 4 6 return result
Transpose: A Trickier Example def transpose(table): """Returns: copy of table with rows and columns swapped 1 2 Precondition: table is a (non-ragged) 2d List""" 3 4 numrows = len(table) # Need number of rows numcols = len(table[0]) # All rows have same no. cols 5 6 result = [] # Result (new table) accumulator for m in range(numcols): # Get the column elements at position m # Make a new list for this column 1 3 5 # Add this row to accumulator table 2 4 6 return result
Transpose: A Trickier Example def transpose(table): """Returns: copy of table with rows and columns swapped 1 2 Precondition: table is a (non-ragged) 2d List""" 3 4 numrows = len(table) # Need number of rows numcols = len(table[0]) # All rows have same no. cols 5 6 result = [] # Result (new table) accumulator for m in range(numcols): row = [] # Single row accumulator for n in range(numrows): 1 3 5 row.append(table[n][m]) # Create a new row list 2 4 6 result.append(row) # Add result to table return result
Transpose: A Trickier Example def transpose(table): """Returns: copy of table with rows and columns swapped 1 2 Precondition: table is a (non-ragged) 2d List""" 3 4 numrows = len(table) # Need number of rows numcols = len(table[0]) # All rows have same no. cols 5 6 result = [] # Result (new table) accumulator Accumulator Accumulator for m in range(numcols): for each loop for each loop row = [] # Single row accumulator for n in range(numrows): 1 3 5 row.append(table[n][m]) # Create a new row list 2 4 6 result.append(row) # Add result to table return result
Relationship to Standard Lists • Functions on nested lists similar to lists § Do not loop over the list (modifying it) § Loop over range of positions instead § No accumulator or return statement • But one important difference § May need multiple for-loops § Depends on if modifying rows or entries
Simple Example def add_ones(table): """Adds one to every number in the table 1 3 5 Preconditions: table is a 2d List, all table elements are int""" 2 4 6 Do not loop Do not loop # Walk through table over the table over the table for rpos in range(len(table)): # Walk through each column for cpos in range(len(table[rpos])): 2 4 6 table[rpos][cpos] = table[rpos][cpos]+1 3 5 7 # No return statement
Simple Example def add_ones(table): """Adds one to every number in the table 1 3 5 Preconditions: table is a 2d List, all table elements are int""" 2 4 6 Note that # Walk through table ragged is okay for rpos in range(len(table)): # Walk through each column for cpos in range(len(table[rpos])): 2 4 6 table[rpos][cpos] = table[rpos][cpos]+1 3 5 7 # No return statement
Another Example def strip(table,col): """Removes column col from the given table 1 3 5 Preconditions: table is a (non-ragged) 2d List, col valid column""" 2 4 6 Do not loop # Walk through table over the table for rpos in range(len(table)): # Modify each row to slice out column table[rpos] = table[rpos][:col] + table[rpos][col+1:] 1 5 2 6 # No return statement
Recommend
More recommend