Questions / Quant development, Python correctness

A shallow copy shares children

Foundation, about 6 minutes. Question D002.

After this Python code, what is len(a[0])?

a = [[1], [2]]
b = a.copy()
b[0].append(9)

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: 2 length

  1. The outer list is copied, but its nested list is shared. Appending through b[0] also changes a[0].

Interview shortcut. .copy() is shallow: inner lists are shared.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More python correctness questions