Predict the output
What does this print?
def a(xs: list[int]) -> None:
xs = [0] * len(xs)
def b(xs: list[int]) -> None:
xs[:] = [0] * len(xs)
u, v = [1, 2], [1, 2]
a(u)
b(v)
print(u, v)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [1, 2] [0, 0]
Right: a rebinds its local name; b writes into the caller's list.
Both functions build the same new list; only the way it is stored differs, which is why the callers see different results.
Why not the others?
- B [0, 0] [0, 0]. a never touches the caller's list; it only rebinds
xs. - C [1, 2] [1, 2]. Slice assignment in b changes the original list.