Skip to content

Python interview practice/Python Developer

Avoid shared mutable default arguments

Mediumpython-core · mutable-defaults

The problem

Implement independent_batches(first, second). Call a nested add_batch function twice without providing its optional accumulator. Return the two independent collected lists.

Function: def independent_batches(first,second):

Example input (a JSON list of arguments): [[1, 2], [3]]
Expected output: [[1, 2], [3]]

Inputs satisfy the problem statement. Sequences contain at most 200 elements unless a smaller bound is stated. Use JSON values and the supplied function signature.

Hints

  1. Use None as the default accumulator and allocate a list inside the call.
  2. Check the supplied examples, empty/boundary cases and the stated answer policy before optimizing.

Worked answer

Try it yourself first. When you are ready, open the answer below.

Show the Python answer
def independent_batches(first,second):
    def add_batch(values,acc=None):
        if acc is None:acc=[]
        acc.extend(values);return acc
    return [add_batch(first),add_batch(second)]

Why it works

Use None as the default accumulator and allocate a list inside the call. A mutable default object is created once at function definition, so subsequent independent calls would otherwise share it.

Complexity: O(n+m) time / O(n+m) output space.

Time: O(n+m) time · Space: O(n+m) output space

Run your own solution

Inside your account you write the code in the browser, run it against hidden test cases and save your attempt. Access covers every track, including the rest of Python Developer.

See access and price

More free Python Developer questions

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.