out = sorted(table, ...), then out[0][0] = 99. Does the caller's table change?
Pick one to see what it prints.
The caller's second row changed. sorted builds a new outer list, but its rows are the input's rows, so a write to the result is a write to the input. Slicing does the same. With no steps at all it's worse: run(table, []) returns the very same list, not a copy.
list(table) doesn't fix it. It's a shallow copy: a new outer list that holds the same rows. Copy each row instead:
Copy
Outer list
Rows
list(table)
new
the same rows: one set, shared
[list(row) for row in table]
new
new lists: two sets, none shared
Copy once, before the first step:
def apply(table, steps): check(steps) table = [list(row) for row in table] return run(table, steps)
The values are numbers, which can't be changed in place, so copying the rows copies everything that can change. After that, the steps can share rows among themselves as much as they like, because every row belongs to this call.
On a table of 1,000 rows by 100 columns:
Copy
Time
Shares rows with the input?
list(table)
0.001 ms
yes
[list(row) for row in table]
0.268 ms
no
copy.deepcopy(table)
15.339 ms
no
deepcopy is 57 times slower here. It makes a Python call for every number too, and it records every list in its memo. Use it when the values themselves can change, like a dict in each cell.
In the editor, write apply(table, steps): check every step, copy the rows, then run. ARITY and run are the ones above, and args_ok(name, args) is the RULES check in one call: it returns RULES[name](*args).
Pick an answer above to see the rest
Instructions
1
Write apply(table, steps). First check every step. Raise ValueError for an unknown name, the wrong number of arguments, or arguments that args_ok(name, args) rejects. Only then run the steps with run, on a copy of table that shares no row with it. ARITY, args_ok and run are defined as in the lesson.