- Static Allocation
# create a 2d list with fixed values (static allocation)
a = [ [ 2, 3, 4 ] , [ 5, 6, 7 ] ]
print(a)
- Dynamic (Variable-Length) Allocation
- Wrong: Cannot use * (Shallow Copy)
# Try, and FAIL, to create a variable-sized 2d list
rows = 3
cols = 2
a = [ [0] * cols ] * rows # Error: creates shallow copy
# Creates one unique row, the rest are aliases!
print("This SEEMS ok. At first:")
print(" a =", a)
a[0][0] = 42
print("But see what happens after a[0][0]=42")
print(" a =", a)
- Right: make2dList()
def make2dList(rows, cols, defaultValue=None):
a=[]
for row in range(rows): a.append([defaultValue]*cols)
return a
rows = 3
cols = 2
a = make2dList(rows, cols, 0)
print("This still is ok. At first:")
print(" a =", a)
a[0][0] = 42
print("But now see what happens after a[0][0]=42")
print(" a =", a)
- Getting 2d List Dimensions
# Create an "arbitrary" 2d List
a = [ [ 2, 3, 5] , [ 1, 4, 7 ] ]
print("a = ", a)
# Now find its dimensions
rows = len(a)
cols = len(a[0])
print("rows =", rows)
print("cols =", cols)
- Nested Looping over 2d Lists
# Create an "arbitrary" 2d List
a = [ [ 2, 3, 5] , [ 1, 4, 7 ] ]
print("Before: a =", a)
# Now find its dimensions
rows = len(a)
cols = len(a[0])
# And now loop over every element
# Here, we'll add one to each element,
# just to make a change we can easily see
for row in range(rows):
for col in range(cols):
# This code will be run rows*cols times, once for each
# element in the 2d list
a[row][col] += 1
# Finally, print the results
print("After: a =", a)
- Printing 2d Lists
def print2dList(a):
# For a nicer but more complex version, see http://goo.gl/eiZ42n
print('[')
for row in range(len(a)):
print(' ', a[row])
print(']')
# Let's give the new function a try!
a = [ [ 1, 2, 3 ] , [ 4, 5, 67 ] ]
print2dList(a)
- Copying 2d Lists
import copy
print('Ways that do not work:')
a = [ [1], [2] ]
b = a + [ ]
c = copy.copy(a)
a[0][0] = 42
print(b) # Fail!
print(c) # Fail!
print()
print('Must use copy.deepcopy for 2d lists:')
a = [ [1], [2] ]
b = copy.deepcopy(a)
a[0][0] = 42
print(b) # Success!